body:
I'm trying to create a security door system that uses an RFID and fingerprint sensor (Adafruit) to allow/deny access to a door. I have the fingerprint sensor and RFID hooked up to an LED, but the code isn't working very well. I want the LED to light only and only when both fingerprints and RFID are verified. Here is my preliminary code.

    //HEADERFILES
    #include <SPI.h> //rfid
    #include <MFRC522.h>//rfid
    #include <Adafruit_Fingerprint.h> //FINGERPRINT
    #include <SoftwareSerial.h> //FINGERPRINT
    #include<stdint.h> //FINGERPRINT

    //rfid settings
    #define RST_PIN         9          // rfid pin 9 RST_pin
    #define SS_PIN          10         // rfid pin 10 SS_pin
    MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance
    String read_rfid;
    String ok_rfid_1 = "cbb427b2"; //white card
    String ok_rfid_2 = "0ebb14f39"; //blue key chain

    //fingerprint settings
    int getFingerprintIDez();
    // pin #2 is IN from sensor (GREEN wire)
    // pin #3 is OUT from arduino  (YELLOW wire)
    SoftwareSerial mySerial(2, 3);
    //activates serial communication on pin 2 & 3
    Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

    //output garage door pin
    int door = 7; //motor to door

    void dump_byte_array(byte * buffer , byte bufferSize) { //why so important
      read_rfid = "";
      for (byte i = 0; i < bufferSize; i++) {
        read_rfid = read_rfid + String(buffer[i], HEX);
      }
    }

    void setup() {
      //RFID setup
      Serial.begin(9600);
      // Initialize serial communications with the PC
      while (!Serial);
      // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
      finger.begin(57600);
      SPI.begin(); // Init SPI bus
      mfrc522.PCD_Init(); // Init MFRC522 RFID
      pinMode (door, OUTPUT);
      //FINGERPRINT setup
      {
        while (!Serial);  // For Yun/Leo/Micro/Zero/...
        if (finger.verifyPassword()) {
          Serial.println("Found fingerprint sensor!");
        } else {
          Serial.println("Did not find fingerprint sensor :(");
          while (1);
        }
        Serial.println("Waiting for valid finger...");
      }

    }

    // OK success!

    p = finger.image2Tz();
    switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
    }
    }

    //DOOR/OUTPUT PIN PROPERTIES CHANGE TO REFLECT HOW FAST AND HOW LONG MOTOR     PULLS DOOR USING DIGITALWRITE; BREAK..   //USING LED FOR NOW

    void open_door() {
      digitalWrite (door, HIGH);
      delay (2000);
      digitalWrite (door, LOW);
    }

    void loop() {
      // RFID LOOP SETTINGS                                                   `
      if ( ! mfrc522.PICC_IsNewCardPresent()) {     // Look for new cards
        return;
      }
      if ( ! mfrc522.PICC_ReadCardSerial()) {       // Select one of the c ards
        return;
      }
      dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
      Serial.println(read_rfid);
      // FINGERPRINT LOOP SETTINGS

      getFingerprintID();  // start fingerprint sensor
      delay(100);

      uint8_t getFingerprintID() {
        uint8_t p = finger.getImage();
        switch (p) {
          case FINGERPRINT_OK:
            Serial.println("Image taken");
            break;
          case FINGERPRINT_NOFINGER:
            Serial.println("No finger detected");
            return p;
          case FINGERPRINT_PACKETRECIEVEERR:
            Serial.println("Communication error");
            return p;
          case FINGERPRINT_IMAGEFAIL:
            Serial.println("Imaging error");
            return p;
          default:
            Serial.println("Unknown error");
            return p;
        }

        p = finger.fingerFastSearch();
        if (p == FINGERPRINT_OK && read_rfid == ok_rfid_1) {
          Serial.println(ok_rfid_1);
          open_door();
        }

      }

**And this is the error I am getting**

    Arduino: 1.8.1 (Windows 10), Board: "Arduino/Genuino Uno"

    fingerprint:127: error: expected unqualified-id before '{' token

     {

     ^

    exit status 1
    expected unqualified-id before '{' token

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

I am new to this so please bear with me and explain in childish manner if possible.

title: RFID+Fingerprint sensor code

Answers: 2

body:
Can't say I have read what you posted here or what you're trying to do, however nonetheless I have fixed the errors in your post. This will compile no problem. Good luck with your project.

    #include <Adafruit_Fingerprint.h>
    #include <SoftwareSerial.h>
    int getFingerprintIDez();
    SoftwareSerial mySerial(2, 3);
    Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

    //HEADERFILES
    #include <SPI.h> //rfid
    #include <MFRC522.h>//rfid
    #include<stdint.h> //FINGERPRINT

    //RFID settings
    #define RST_PIN         9          // RFID pin 9 RST_pin
    #define SS_PIN          10         // RFID pin 10 SS_pin
    MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance
    String read_rfid;
    String ok_rfid_1 = "cbb427b2"; //white card
    String ok_rfid_2 = "0ebb14f39"; //blue key chain

    int door = 7; //motor to door

    void dump_byte_array(byte * buffer , byte bufferSize) {
      //why so important
      read_rfid = "";
      for (byte i = 0; i < bufferSize; i++) {
        read_rfid = read_rfid + String(buffer[i], HEX);
      }
    }

    void setup() {
      //RFID setup
      finger.begin(57600);
      Serial.begin(9600);
      // Initialize serial communications with the PC
      while (!Serial);
      // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
      SPI.begin(); // Init SPI bus
      mfrc522.PCD_Init(); // Init MFRC522 RFID
      pinMode (door, OUTPUT);
      //FINGERPRINT setup
      {
        while (!Serial);  // For Yun/Leo/Micro/Zero/...
        if (finger.verifyPassword()) {
          Serial.println("Found fingerprint sensor!");
        } else {
          Serial.println("Did not find fingerprint sensor :(");
          while (1);
        }
        Serial.println("Waiting for valid finger...");
      }
    }

    // OK success!

    void open_door() {
      digitalWrite (door, HIGH);
      delay (2000);
      digitalWrite (door, LOW);
    }

    void loop() {
      // RFID LOOP SETTINGS
      if (! mfrc522.PICC_IsNewCardPresent()) {
        // Look for new cards
        return;
      }
      if (!mfrc522.PICC_ReadCardSerial()) {
        // Select one of the cards
        return;
      }
      dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
      Serial.println(read_rfid);
      // FINGERPRINT LOOP SETTINGS
      getFingerprintID();  // start fingerprint sensor
      delay(100);
    }

    uint8_t getFingerprintID() {
      uint8_t p = finger.getImage();
      switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image taken");
          break;
        case FINGERPRINT_NOFINGER:
          Serial.println("No finger detected");
          return p;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          return p;
        case FINGERPRINT_IMAGEFAIL:
          Serial.println("Imaging error");
          return p;
        default:
          Serial.println("Unknown error");
          return p;
      }

      // OK success!
      p = finger.image2Tz();
      switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image converted");
          break;
        case FINGERPRINT_IMAGEMESS:
          Serial.println("Image too messy");
          return p;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          return p;
        case FINGERPRINT_FEATUREFAIL:
          Serial.println("Could not find fingerprint features");
          return p;
        case FINGERPRINT_INVALIDIMAGE:
          Serial.println("Could not find fingerprint features");
          return p;
        default:
          Serial.println("Unknown error");
          return p;
      }

      // OK converted!
      p = finger.fingerFastSearch();
      if (p == FINGERPRINT_OK) {
        Serial.println("Found a print match!");
      } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
        Serial.println("Communication error");
        return p;
      } else if (p == FINGERPRINT_NOTFOUND) {
        Serial.println("Did not find a match");
        return p;
      } else {
        Serial.println("Unknown error");
        return p;
      }
      // found a match!
      Serial.print("Found ID #"); Serial.print(finger.fingerID);
      Serial.print(" with confidence of "); Serial.println(finger.confidence);
    }

body:
    default:
      Serial.println("Unknown error");
      return p;
    }
    } <-- Why?

Proper indentation shows that you have an extraneous closing curly brace.


body:
I'm having some problem with the [MPU6050 example sketch][1]. I added a few bits of code of my own, so that my LEDs change color based on the yaw-pitch-roll. However when I try to run it, the values of the yaw-pitch-roll get all distorted, like this:

    ypr -38.68  -30.05  41.34
    ypr -55.42  -35.25  -31.68
    ypr -101.02 23.53   -65.01
    ypr 101.29  -19.63  12.81
    ypr -51.97  -37.49  44.85
    ypr 37.89   38.20   -37.95
    ypr 72.15   -13.70  22.68
    ypr 0.00    0.00    90.00
    ypr -45.73  74.52   -11.89
    ypr 134.36  31.89   -31.08
    ypr -13.86  -21.51  3.54

And when I disable `analogWrite` on the LED lights the yaw-pitch-roll gives normal output again.

Below is the code for changing the LED colors.

    void setColor (float red, float blue){
      int redColor = (int)255 - red;
      int blueColor = (int)255 - blue;
      analogWrite(redPin, redColor);
      analogWrite(bluePin, blueColor);
    }

Does anyone know what is going wrong here?

EDIT:

The wiring:

[![Wiring of my project][2]][2]

The code:

    // I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
    // for both classes must be in the include path of your project
    #include "I2Cdev.h"

    #include "MPU6050_6Axis_MotionApps20.h"
    //#include "MPU6050.h" // not necessary if using MotionApps include file

    // Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation is used in I2Cdev.h
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        #include "Wire.h"
    #endif

    // class default I2C address is 0x68
    // specific I2C addresses may be passed as a parameter here
    // AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
    // AD0 high = 0x69
    MPU6050 mpu;
    //MPU6050 mpu(0x69); // <-- use for AD0 high

    // uncomment "OUTPUT_READABLE_QUATERNION" if you want to see the actual
    // quaternion components in a [w, x, y, z] format (not best for parsing
    // on a remote host such as Processing or something though)
    //#define OUTPUT_READABLE_QUATERNION

    // uncomment "OUTPUT_READABLE_EULER" if you want to see Euler angles
    // (in degrees) calculated from the quaternions coming from the FIFO.
    // Note that Euler angles suffer from gimbal lock (for more info, see
    // http://en.wikipedia.org/wiki/Gimbal_lock)
    //#define OUTPUT_READABLE_EULER

    // uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/
    // pitch/roll angles (in degrees) calculated from the quaternions coming
    // from the FIFO. Note this also requires gravity vector calculations.
    // Also note that yaw/pitch/roll angles suffer from gimbal lock (for
    // more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)
    #define OUTPUT_READABLE_YAWPITCHROLL

    // uncomment "OUTPUT_READABLE_REALACCEL" if you want to see acceleration
    // components with gravity removed. This acceleration reference frame is
    // not compensated for orientation, so +X is always +X according to the
    // sensor, just without the effects of gravity. If you want acceleration
    // compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.
    //#define OUTPUT_READABLE_REALACCEL

    // uncomment "OUTPUT_READABLE_WORLDACCEL" if you want to see acceleration
    // components with gravity removed and adjusted for the world frame of
    // reference (yaw is relative to initial orientation, since no magnetometer
    // is present in this case). Could be quite handy in some cases.
    //#define OUTPUT_READABLE_WORLDACCEL

    // uncomment "OUTPUT_TEAPOT" if you want output that matches the
    // format used for the InvenSense teapot demo
    //#define OUTPUT_TEAPOT

    #define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
    bool blinkState = false;

    // MPU control/status vars
    bool dmpReady = false;  // set true if DMP init was successful
    uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
    uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
    uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
    uint16_t fifoCount;     // count of all bytes currently in FIFO
    uint8_t fifoBuffer[64]; // FIFO storage buffer

    // orientation/motion vars
    Quaternion q;           // [w, x, y, z]         quaternion container
    VectorInt16 aa;         // [x, y, z]            accel sensor measurements
    VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
    VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
    VectorFloat gravity;    // [x, y, z]            gravity vector
    float euler[3];         // [psi, theta, phi]    Euler angle container
    float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

    // packet structure for InvenSense teapot demo
    uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };

    int redPin = 11;
    int bluePin = 9;

    int startR = 100;
    int startB = 10;

    int eindR = 255;
    int eindB = 255;

    int gyroMin = 0;
    int gyroMax = 80;
    int gyroRange = 0;
    float rangeR = 0;
    float rangeB = 0;

    // ================================================================
    // ===               INTERRUPT DETECTION ROUTINE                ===
    // ================================================================

    volatile bool mpuInterrupt = false; // indicates whether MPU interrupt pin has gone high
    void dmpDataReady() {
        mpuInterrupt = true;
    }

    void setup() {
        // join I2C bus (I2Cdev library doesn't do this automatically)
        #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
            Wire.begin();
            TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
        #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
            Fastwire::setup(400, true);
        #endif

        gyroRange = (gyroMax - 10) - (gyroMin + 10);
        rangeR = (float)(eindR - startR)/gyroRange;
        rangeB = (float)(eindB - startB)/gyroRange;

        Serial.begin(115200);
        while (!Serial);

        // initialize device
        Serial.println(F("Initializing I2C devices..."));
        mpu.initialize();

        // verify connection
        Serial.println(F("Testing device connections..."));
        Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

        // wait for ready
        Serial.println(F("\nSend any character to begin DMP programming and demo: "));
        /*while (Serial.available() && Serial.read()); // empty buffer
        while (!Serial.available());                 // wait for data
        while (Serial.available() && Serial.read()); // empty buffer again*/

        // load and configure the DMP
        Serial.println(F("Initializing DMP..."));
        devStatus = mpu.dmpInitialize();

        // supply your own gyro offsets here, scaled for min sensitivity
        mpu.setXGyroOffset(220);
        mpu.setYGyroOffset(76);
        mpu.setZGyroOffset(-85);
        mpu.setZAccelOffset(1); // 1688 factory default for my test chip

        // make sure it worked (returns 0 if so)
        if (devStatus == 0) {
            // turn on the DMP, now that it's ready
            Serial.println(F("Enabling DMP..."));
            mpu.setDMPEnabled(true);

            // enable Arduino interrupt detection
            Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
            attachInterrupt(0, dmpDataReady, RISING);
            mpuIntStatus = mpu.getIntStatus();

            // set our DMP Ready flag so the main loop() function knows it's okay to use it
            Serial.println(F("DMP ready! Waiting for first interrupt..."));
            dmpReady = true;

            // get expected DMP packet size for later comparison
            packetSize = mpu.dmpGetFIFOPacketSize();
        } else {
            // ERROR!
            // 1 = initial memory load failed
            // 2 = DMP configuration updates failed
            // (if it's going to break, usually the code will be 1)
            Serial.print(F("DMP Initialization failed (code "));
            Serial.print(devStatus);
            Serial.println(F(")"));
        }

        // configure LED for output
        pinMode(LED_PIN, OUTPUT);
        pinMode(redPin, OUTPUT);
        pinMode(bluePin, OUTPUT);
        //digitalWrite(redPin, LOW);
        //digitalWrite(bluePin, LOW);
        setColor(100.0,100.0);
    }

    void loop() {
        // if programming failed, don't try to do anything
        if (!dmpReady) return;

        // wait for MPU interrupt or extra packet(s) available
        while (!mpuInterrupt && fifoCount < packetSize) {
            // other program behavior stuff here
        }

        // reset interrupt flag and get INT_STATUS byte
        mpuInterrupt = false;
        mpuIntStatus = mpu.getIntStatus();

        // get current FIFO count
        fifoCount = mpu.getFIFOCount();

        // check for overflow (this should never happen unless our code is too inefficient)
        if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
            // reset so we can continue cleanly
            mpu.resetFIFO();
            Serial.println(F("FIFO overflow!"));
            } else if (mpuIntStatus & 0x02) {
              // otherwise, check for DMP data ready interrupt (this should happen frequently)
             // wait for correct available data length, should be a VERY short wait
            while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

            // read a packet from FIFO
            mpu.getFIFOBytes(fifoBuffer, packetSize);

            // track FIFO count here in case there is > 1 packet available
            // (this lets us immediately read more without waiting for an interrupt)
            fifoCount -= packetSize;

            #ifdef OUTPUT_READABLE_QUATERNION
                // display quaternion values in easy matrix form: w x y z
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                Serial.print("quat\t");
                Serial.print(q.w);
                Serial.print("\t");
                Serial.print(q.x);
                Serial.print("\t");
                Serial.print(q.y);
                Serial.print("\t");
                Serial.println(q.z);
            #endif

            #ifdef OUTPUT_READABLE_EULER
                // display Euler angles in degrees
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetEuler(euler, &q);
                Serial.print("euler\t");
                Serial.print(euler[0] * 180/M_PI);
                Serial.print("\t");
                Serial.print(euler[1] * 180/M_PI);
                Serial.print("\t");
                Serial.println(euler[2] * 180/M_PI);
            #endif

            #ifdef OUTPUT_READABLE_YAWPITCHROLL
                // display Euler angles in degrees
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetGravity(&gravity, &q);
                mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
                Serial.print("ypr\t");
                Serial.print(ypr[0] * 180/M_PI);
                Serial.print("\t");
                Serial.print(ypr[1] * 180/M_PI);
                Serial.print("\t");
                Serial.println(ypr[2] * 180/M_PI);
                int degree = ypr[1] * 180/M_PI;
                if (degree <= (gyroMin + 10)){
                  setColor(startR, startB);
                }
                if ((degree > (gyroMin + 10)) && (degree < (gyroMax - 10))){
                  float calcR = (startR + ((degree-10) * rangeR));
                  float calcB = (startB + ((degree-10) * rangeB));
                  setColor(calcR,calcB);
                }
                if (degree >= (gyroMax - 10)){
                  setColor(eindR, eindB);
                }
            #endif

            #ifdef OUTPUT_READABLE_REALACCEL
                // display real acceleration, adjusted to remove gravity
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetAccel(&aa, fifoBuffer);
                mpu.dmpGetGravity(&gravity, &q);
                mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
                Serial.print("areal\t");
                Serial.print(aaReal.x);
                Serial.print("\t");
                Serial.print(aaReal.y);
                Serial.print("\t");
                Serial.println(aaReal.z);
            #endif

            #ifdef OUTPUT_READABLE_WORLDACCEL
                // display initial world-frame acceleration, adjusted to remove gravity
                // and rotated based on known orientation from quaternion
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetAccel(&aa, fifoBuffer);
                mpu.dmpGetGravity(&gravity, &q);
                mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
                mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
                Serial.print("aworld\t");
                Serial.print(aaWorld.x);
                Serial.print("\t");
                Serial.print(aaWorld.y);
                Serial.print("\t");
                Serial.println(aaWorld.z);
            #endif

            #ifdef OUTPUT_TEAPOT
                // display quaternion values in InvenSense Teapot demo format:
                teapotPacket[2] = fifoBuffer[0];
                teapotPacket[3] = fifoBuffer[1];
                teapotPacket[4] = fifoBuffer[4];
                teapotPacket[5] = fifoBuffer[5];
                teapotPacket[6] = fifoBuffer[8];
                teapotPacket[7] = fifoBuffer[9];
                teapotPacket[8] = fifoBuffer[12];
                teapotPacket[9] = fifoBuffer[13];
                Serial.write(teapotPacket, 14);
                teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
            #endif

            // blink LED to indicate activity
            blinkState = !blinkState;
            digitalWrite(LED_PIN, blinkState);
        }
    }
    void setColor (float red, float blue){
      int redColor = (int)255 - red;
      int blueColor = (int)255 - blue;
      analogWrite(redPin, redColor);
      analogWrite(bluePin, blueColor);
    }

EDIT 2:
After a lot of testing with and without resistors and new cables (I thought there might be some sort of cable damage), it still isn't working fully. The weird thing is that when every component is hooked up via a breadboard it works (without resistors). But as soon as I try to solder everything it works randomly.

Is there a chance that the type of cable (copper vs aluminium) has any effect on this? The breadboard cables are aluminium and the soldered cables are copper.

  [1]: https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/MPU6050/examples/MPU6050_DMP6
  [2]: https://i.stack.imgur.com/mbojC.png

title: Arduino MPU6050 not working due to LED PWM

Answers: 1

body:
You have no resistors on your LEDs. The PWM signals are causing huge amounts of noise in the MCU corrupting all your data and communications.

Add resistors (say 330Ω) to each LED cathode pin (so 9 resistors).


body:
Here is my challenge: I have to create a sketch where I would have a prompt asking the user to enter an ID. If it is successful, it would turn on the green LED and response with "Hello, your name is so-so."  If it failed, it would turn on the red LED and response with "Invalid username! Try again."

The code is here:

    //Establish myID as CHAR data type
     char myID = 'tg123';
     //Establish testID to receive data to be tested against myID
     char testID;

     //Establish green and red LEDs to PWM pins
     const int gLED = 10;
     const int rLED = 5;

     void setup()
     {
      //Establishing baud rate at 9600
      Serial.begin(9600);
      pinMode(gLED, OUTPUT);
      pinMode(rLED, OUTPUT);
     }

     void loop()
     {
      //Act when there are data in the buffer
      while (Serial.available())
      {
        testID = Serial.read();
        //If data = myID, turn on green LED and acknowledge
        if (testID == myID)
        {
          digitalWrite(gLED, HIGH);
          digitalWrite(rLED, LOW);
          Serial.println("Hello! Your name is Trevor.");
          delay(5000);
        }
        else
        {
          digitalWrite(rLED, HIGH);
          digitalWrite(gLED, LOW);
          Serial.println("Invalid ID! Try again.");
          delay(2000);
        }
      }
     }

Two problems I have had with this:

1. The damn thing would print the line "Please enter your ID:" infinitely if it was inside the loop, so I got fed up and moved it to the set up, and
2. no matter what I enter in the serial monitor, it does not do anything.

Update: After reading Arduino's website, I found I can predefine the char data type by adding `char myID = 'tg123';`.  It is getting closer to achieving what I want, but it's exhibiting some strange behavior.  When I type in exactly tg123 in the serial monitor, it would report the error message as defined in the sketch before passing.

title: Testing ID and Serial Communication (Update)

Answers: 2

body:
When you use the Arduino IDE to compile your code for an Uno, it will tell you

>Sketch uses 2106 bytes (6%) of program storage space. Maximum is 32256 bytes.
Global variables use 237 bytes (11%) of dynamic memory, leaving 1811 bytes for local variables. Maximum is 2048 bytes.

as if there had been a clean and correct compilation.  However, if you compile it via `make` and a makefile (see, eg, [sudar's Arduino Makefile](https://github.com/sudar/Arduino-Makefile)) you will see a warning like the following:

>stringInit1.ino:2:14: warning: character constant too long for its type [enabled by default]
  char myID = 'tg123';

where `stringInit1` stands for whatever you call your sketch.

The `char` data type stands for a single character.  To represent a text string, use either an array of characters (for example, `char *myID = "tg123"` or `char myID[] = "tg123"`) or a `String` type (which, in general, is problematic on small-RAM embedded processors).

Then, to make the comparison, keep track of how many characters have been input so far, and as you input each character, compare it to the current character of `myID`, clearing a match-flag if characters don't match.  Eg, `if (testChar != myID[currentCount]) matchFlag = false;`.  Note, initialize `currentCount` to zero and `matchFlag` to true in `setup()` and before each retry.

body:
You are assigning a string to a single character here.

>char myID = 'tg123';

Instead you should make it a String variable. And compare it after all the characters are recieved.

>String myID = "tg123";

And Here is the modified code you should test with. In this case I have assumed you simply write the ID (string) in serial terminal and hit enter.

N.B. If you want to enter each character one by one, then it will not be able to catch the whole string. For this case you have to add some time-out to wait for next character to arrive.

    String recvData = "";
    void loop()
    {
      while (!Serial.available());
      while (Serial.available())
      {
        char ch = Serial.read();
        recvData += ch;
      }
      if (myID == recvData)
      {
        digitalWrite(gLED, HIGH);
        digitalWrite(rLED, LOW);
        Serial.println("Hello! Your name is Trevor.");
        delay(5000);
      }
      else
      {
        digitalWrite(rLED, HIGH);
        digitalWrite(gLED, LOW);
        Serial.println("Invalid ID! Try again.");
        delay(2000);
      }
      recvData = "";
     }


body:
I've been having this problem, that I am trying to use an accelerometer MPU-6050 to get the rotation and pass that information to Unity.

I also have some buttons in the same Arduino. I'm using an Arduino Uno. With those buttons, everything works well, but the moment I put something related to the accelerometer in the Arduino code, Unity marks a time out. When I run it on Arduino it sends me all the info I'm asking, so I don't really know what's the problem. I really appreciate if someone could help me.

Here is code on Arduino:

    #include<Wire.h>
    #define A_R 16384.0
    #define G_R 131.0
     #define RAD_A_DEG = 57.295779
    const int MPU_addr=0x68;  // I2C address of the MPU-6050
    int AcX,AcY,AcZ,GyX,GyY;

    float Acc[2];
    float Gy[2];
    float Angle[2];
    int button = 0;
    int button2 = 0;
    int button3 = 0;

    float arriba=0, abajo=0,mouse=0;

    void setup(){
      Wire.begin();
      Wire.beginTransmission(MPU_addr);
      Wire.write(0x6B);  // PWR_MGMT_1 register
      Wire.write(0);     // set to zero (wakes up the MPU-6050)
      Wire.endTransmission(true);
      pinMode(7, INPUT); // declare pushbutton as input
    pinMode(6, INPUT);
    pinMode(5,INPUT);
      Serial.begin(9600);
    }

    void loop(){
      Wire.beginTransmission(MPU_addr);
      Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
      Wire.endTransmission(false);
      //Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers

      AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
      AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
     AcZ=Wire.read()<<8|Wire.read();

      Acc[1] = atan(-1*(AcX/A_R)/sqrt(pow((AcY/A_R),2) + pow((AcZ/A_R),2)))*RAD_TO_DEG;
       Acc[0] = atan((AcY/A_R)/sqrt(pow((AcX/A_R),2) + pow((AcZ/A_R),2)))*RAD_TO_DEG;

      GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
      GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)

      Angle[0] = 0.98 *(Angle[0]+Gy[0]*0.010) + 0.02*Acc[0];
       Angle[1] = 0.98 *(Angle[1]+Gy[1]*0.010) + 0.02*Acc[1];

            button = digitalRead(7);
      button2 = digitalRead(6);
      button3 = digitalRead (5);

       //Mostrar los valores por consola
       if(button == HIGH){
     arriba=1;
      }else if(button==LOW){
      arriba=0;
      }

      if(button2 == HIGH){
        abajo=1;
      }else if(button2==LOW){
        abajo=0;
      }

      if(button3 == HIGH){  //boton 3
        mouse=1;
      }else if(button3==LOW){
        mouse=0;
      }
      Serial.print(arriba);
      Serial.print(",");
      Serial.print(abajo);
      Serial.print(",");
      Serial.print(mouse);
       Serial.print(",");

       Serial.print(Angle[0]);
       Serial.print(",");
       Serial.println(Angle[1]);

      delay(200);
    }

I know this isn't an Unity forum, but here is the code in Unity. The only thing it does, is read it and put the results in an array.

<!-- language: c# -->

    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.IO.Ports;
    using System.Globalization;
    using System;

    using UnityEngine;

    public class ConectarArduino: MonoBehaviour
    {
        string Recibidos;
        public string Linea, Linea1,Linea2;
        public int Arrib, Abajo,Boton;
        SerialPort stream;
        // Use this for initialization

        void Start()
        {
            stream = new SerialPort("COM3", 9600);
            //  stream.
            stream.Open();
            stream.ReadTimeout = 300;

        }

        // Update is called once per frame
        void Update()
        {
            try
            {
                Recibidos = stream.ReadLine();
                Debug.Log(Recibidos);
            }
            catch (System.Exception e)
            {
                Debug.Log(e.Message);
                throw;
            }

            string[] Values = Recibidos.Split(',').Select(str => str.Trim()).ToArray();
            Linea = Values[0];
            Linea1 = Values[1];
            Linea2 = Values[2];

title: Accelerometer MPU-6050 marks timeout in Unity

Answers: 1

body:
Running MPU-6050 at 57600bps seemed to be the good rate for me:

      pinMode(5,INPUT);
      Serial.begin(57600);
    }

It worked for me and I found these guys for whom it was the good rate :

From [MPU-6050-simple-library][1], specifically [MPU6050_test.ino][2]:

>     void setup() {
>       Serial.begin(57600);
>       MPU6050mgr.begin(); // Initializes IMU module
>     }

From [Another Arduino as external i2c device for MPU6050][3]:

>     void setup() {
>       Wire.begin(0x1E);                // join i2c bus with address #8
>       Wire.onReceive(receiveEvent); // register event
>       Serial.begin(57600);           // start serial for output
>     }

From [Library for Arduino and MPU-6050 communication][4]:

>     void setup() {
>       Serial.begin(57600);
>       MPU6050mgr.begin(); // Initializes IMU module
>     }

You may also find this link useful: [MPU-6050 Redux: DMP Data Fusion vs. Complementary Filter][5].

  [1]: https://github.com/dadez87/MPU-6050-simple-library
  [2]: https://github.com/dadez87/MPU-6050-simple-library/blob/master/MPU6050_test/MPU6050_test.ino
  [3]: https://www.i2cdevlib.com/forums/topic/538-another-arduino-as-external-i2c-device-for-mpu6050/
  [4]: https://www.monocilindro.com/2017/02/25/library-arduino-mpu-6050-communication/
  [5]: http://www.geekmomprojects.com/mpu-6050-redux-dmp-data-fusion-vs-complementary-filter/


body:
I'm using an Attiny85 to interact with a computer using an USB connection, and everything works fine except when I restart my computer and the Attiny85 is connected. When Windows end to boot up the Attiny85 isnt't recognized, and on Device Manager it's listed like this:

[![Unknown USB Device (Device Descriptor Request Failed)][1]][1]

If I unplug the Attiny85 and then plug it back in, everything works just fine.

Is there any to make it detectable at boot time without having to always unplug/plug it?

**EDIT:**

More details:

I'm using this board
[![ATtiny85 USB Mini Dev Board][2]][2]

and **libusb-win32** as the USB driver

  [1]: https://i.stack.imgur.com/bSScC.png
  [2]: https://i.stack.imgur.com/IAxPj.png

title: Attiny85 not recognized at windows startup

Answers: 1

body:
I don't have enough reputations to make a comment so I will drop my 2 cents here.

There should be more elegant way to do this but as a fast solution I would recommend two things:

1. If it is possible, add a push button to your board to reset the MCU manually when the PC is booted up.

2. You can make a software reset after powering up the board by a certain time (e.g. 10 sec) by using watchdog timer.


body:
Is there any limitation to connecting more strips?

I plan to create for my temple [Ganpati Street Lighting LED Decoration - Full HD Ahmednagar Mh India][1]

Watch this video and give me some ideas and suggestions.

  [1]: https://www.youtube.com/watch?v=VeGUrpI-5oQ

title: How many WS2811 LED strips can I control with Arduino?

Answers: 3

body:
There are three factors to consider when driving strings of these LEDs from an Arduino:

1. How much memory the Arduino has - each LED takes at least 3 bytes of RAM (possibly more depending on the library implementation). (An Uno could probably just manage 500 at most)
2. How long it takes to send the data over the wire - the more LEDs you have in a chain the longer each update takes and the slower your animations run.
3. How you power such a huge number of LEDs efficiently. You won't just plug them into the 5V pin of the Arduino that's for sure.

Note that the arrangement you link to most likely isn't a single small microcontroller controlling the whole lot. Instead it is much more likely each individual strip has a single controller and those controllers are all networked together (probably through RS-485 or CAN) to a master controller (probably a PC) to send instructions to them all.

body:
Majenko is totally right (as always).

But as an alternative solution, you could opt for SPI-based LEDstrips. They're not bound to specific timings and thus:

 1. You can "generate"/stream colors. You can let your Arduino calculate the next color and send it directly. In this way, you'll only need RAM for one pixel at the time. For the length, you're now only limited to the time it takes to update a strip.
 2. Sending of data in SPI is done in hardware and can thus be done by hardware, while your software focusses on the next job/pixel. (So you also don't need to calculate the whole strip at once, before sending)
 3. Often, you can send "pixels" much faster, by simply increasing your SPI clock. I'm not sure what the limit will be here, check the ledstrip datasheets.

Also, if you're going to push the limit of Arduino, why not use better hardware? The Teensy 3.2 is often used for ledstrip projects, since it has 64K ram and 256K flash and can run at 96Mhz  (not sure about the SPI speed). Have a look at fastled and octows as well.

You should split up this project, to make it scalable. Try to make one "row" of it and start adding more rows (with individual controllers and power).

I agree with Majenko on using RS485 or CAN to connect/command/sync these different rows.

body:
I have worked with setups similar to this. Arduino is limited as mentioned by Majenko.

If you like the Arduino platform I recommend you look into the Teensy based controllers.  They are 32 bit based and have more memory and are optimized to handle LED projects like this. Best of all, it uses the Arduino IDE with numerous libraries.  The Teensy would need to be paired with a Network adapter, so you could use sACN E1.31 and use software like Jinx to create the effects you're wanting to do.


body:
I have a Geeetech Iduino Yun Shield. I accidentally flashed [the wrong firmware image](https://www.arduino.cc/en/Tutorial/YunSysupgrade) (not the sysupgrade) to the board. I then tried using the [Yun UBoot Reflash](https://www.arduino.cc/en/Tutorial/YunUBootReflash) method. However, when I open the console monitor from the IDE and restart/reboot the board, I do not get the UBoot prompt. I have attempted to run it at least ten times without receiving any console/serial output.

*EDIT*: The shield is running on a Leonardo base board.

Is there anything I can do to load the correct firmware onto the board and get it operational or is the board truly bricked? If so, is it possible to obtain a new Atheros AR9331 board to replace the existing one or should I buy a new Yun?

**Update**: I have tried to get the shield to do an FTP boot, [as detailed here by Majenko](https://hackingmajenkoblog.wordpress.com/2016/02/24/fixing-the-dragino-yun-board/). I get to the stage where I get the `dr_boot>` prompt. However, when I type in `tftpboot 0x81000000 dragino2-yun-common-v2.0.6-kernel.bin`, I get no feedback; it just sits there indefinitely (unless I interupt the process). I can't figure out what I'm doing wrong.

title: Yun UBoot Prompt Not Showing

Answers: 1

body:
The shield is very different to the real Yun when it comes to serial communication.

Typically the Atheros's UART is mapped to pins 0/1 of the shield for communication with the board it is plugged in to. Those pins are also the pins you use to communicate with the PC, so the normal YunSerialTerminal sketch can't be used.

Instead you will have to lift those pins out of the socket they go into (depending on the shield you may just be able to bend them slightly) and then manually connect them (along with ground) to an external USB to UART adaptor (e.g., FT232) to use for the communication.  Nothing needs to be installed into the Arduino board since that is now just being used as a power supply.

See [this answer](https://arduino.stackexchange.com/a/38448/25757) for which pins to use to run the shield stand-alone.


body: I got a makeblock Arduino. Sometimes when I make it go forward at full speed, all motors stop for 3 seconds and it beeps shortly. I think it is that the motors are a little hard to turn for a moment and it stops to prevent damage to the motors. It is getting very annoying. Is there any way to disable it or make it less sensitive?

title: Makeblock Arduino keeps stopping from motor overpower protection

Answers: 1

body:
It is unlikely the pause in operation is because of the motors.  It is more likely the [Makeblock][1] is stopping because the  motor controllers are too hot.  Next time try to identify which chips on the board are controlling the motors and test if they are getting hot to the touch.  If so, consider adding heat sinks to these chips to mitigate any heat dissipation problems.

An alternative explanation involves a limited power supply.  It could be that when the motors are demanding high current, the voltage drops and the processor resets.  Consider a power supply that can offer more amperage.  Or larger capacity batteries.

  [1]: http://wiki.makeblock.cc/index.php?title=Getting_Started_with_Makeblock


body:
I have a HC-SR04 sensor mounted on a stepper motor, mounted on a car.
The idea is this:

 - The car moves forward with the ultrasonic sensor facing the front
 - If the sensor reads a small distance the car do the following:
       - Stop
       - Turn the sensor to the left and get a new distance
       - Turn the sensor to the Right and get a new distance
       - Drive slightly backward
       - The car turns the to direction the distance was the highest
       - Drive forward again

I think I must have wrongly understood how the echo/ultrasonic sensor works. Because when I read values to the left and right, it will always return zero, but reading values when driving forward works very well.

Below is the relevant code

    //Trigger
    void triggerEcho(){
      digitalWrite(echoTrigPin,LOW);
      delayMicroseconds(5);
      digitalWrite(echoTrigPin,HIGH);
      delayMicroseconds(10);
      digitalWrite(echoTrigPin,LOW);
    }

    //Trigger, receive and calculate distance (cm)
    long getEchoDistance(){
      triggerEcho();
      pinMode(echoRecPin, INPUT);
      long echoDuration = pulseIn(echoRecPin, HIGH);

      return echoDuration / 58;
    }

    void loop(){

      long distance = getEchoDistance();

      //If front obstacle is encountered
      if((distance < 5) && (distance != 0)){
          carStop();
          servo.write(180);                     //turn echo sensor left
          delay(250);
          long distanceL = getEchoDistance();   //trigger and read sensor value
          servo.write(0);                       //turn echo sensor right
          delay(250);
          long distanceR = getEchoDistance();   //trigger and read sensor value

          //this will always show distance as 0
          Serial.print("  LEFT :"); Serial.print(distanceL); Serial.print("\n");
          Serial.print("  RIGHT:"); Serial.print(distanceR); Serial.print("\n");

          carDriveBackward(135, 1.185, 1.0);     //drive backwards
          delay(250);
          if(distanceR>distanceL)                //turn in the direction that was furthest
            carTurnRight(100,1250);
          else
            carTurnLeft(100,1250);
          carStop();
          servo.write(90);                        //face sensor forward
          delay(250);
        }
        else
          carDriveForward(135, 1.185, 1.0); //R - L
    }

I bet something is wrong with how I'm implementing the `triggerEcho()` and `getEchoDistance()`. I excluded anything on the wiring and pins, as the reading of the distance is very correct when reading the facing the front.

title: HC-SR04 pulse at multiple angles

Answers: 1

body:
I doubt you have misunderstood the way ultra sound works.  You send a pulse and then go quiet waiting for a reply.  The time it takes to send the pulse is the minimum distance you can detect things at.

If you are not getting returns left and right then it could be there is nothing there or turning the head is breaking a connection.

Firstly jack the vehicle up off the floor so it doesn't go anywhere.
Place a solid object (book) in front of the vehicle and make sure it detects it.
Now place the same object to the right of the vehicle, do it detect it?
Stop the US sensor when it is looking right (by killing the power) and check that it is looking horizontally.  Check the connections, are they being pulled loose?

Your code looks fine, you US works forwards so I think it is a mechanical issue with your car.


body:
I've set up a Yun before to use the handshake line on pin 7 (thanks to [this great forum post][1]) and now I have a new project that I want to do something similar with the Tian. Based on the [schematic][2], it's a similar idea: set the output, mark the output low. But so far I haven't been able to get it working. Anyone know how to adopt the following command from /etc/rc.local to the Tian?

    # Added section to set the handshake line.
    # GP19 is connected to D7 of the 32U4 processor.
    # This requires setting GP22 high to enable the U7 level shifter.
    # This GPIO is already exported.
    # Then GP19 needs to be exported, set to output, and finally brought low.
    echo 1 > /sys/class/gpio/gpio15/value
    echo 21 > /sys/class/gpio/export
    echo "high" > /sys/class/gpio/gpio21/direction
    echo 0 > /sys/class/gpio/gpio21/value

This code is what I'm using now: it's the forum poster's text with my updates for the Tian.

  [1]: https://forum.arduino.cc/index.php?topic=290149.msg2029465#msg2029465
  [2]: http://download.arduino.org/products/TIAN/TIAN-V03-20160219.pdf

title: Using the Tian handshake line

Answers: 0


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

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

I'm newbie in Arduino programming so I hope to get a clear answer.

I have NodeMCU v1 12-E, I connected it with RFID RC522 as in attachment picture.

Now my question:
I need to connect I2C interface LCD module with it to print some words in.
The RFID use the default SDA and SCL pins on NodeMCU V1.0 "D1 and D2" also when I see wiring for the LCD I2C it use same D1 and D2 pins.
So now if I change the RFID instance creation code to

    MFRC522 mfrc522(0,2);

    //SS_PIN 3 RST_PIN 4

Is the RFID will work as previous pins and the LCD will work also?

title: NodeMCU with RFID RC522 and I2C interface LCD module together

Answers: 1

body: You can have multiple devices on the I2C bus so long as they all have different addresses.  This means you should be able to connect D1 and D2 to the RFID and LCD.  HOWEVER I'm not sure that you are using I2C to talk to the RFID board, if you aren't then you may need to move the RFID boards pins and leave I2C on D1&2.


body:
This is my first post to Stack Exchange so please forgive any formatting errors.

I am conducting an experiment that has 7 total sensors: 5 thermocouples, 2 humidity sensors and 1 pressure sensor. I am reading their signals via Arduino Mega analog input ports. I chose to use Python to save and compile the data in a nice csv file, therefore I am using Pyserial.

My problem is that I cannot go above 1 sample/second. As you can see in my code, I have a 1 second delay in Arduino and Python. I have ran successful calibration tests with my thermocouples, so I know at that rate Python and Arduino are communicating well. Anything faster than 1 sample/second (i.e. I change my delays to .5 or .25 seconds), a timing error occurs and my data is "cut up" and sent in odd chunks instead of the standard layout I programmed.

Additionally, I tried to increase the baud rate from 9600 and anything above that will send "garbage" ASCII characters (e.g. little blank blocks and odd characters) to the Serial Comm. I changed the baud rate in Arduino, Python *and* the COM port in my devices manager settings to no avail.

I would really like to increase my sampling rate to increase my signal-to-noise ratio and I believe it's good practice as a metrologist to have a higher sampling rate than 1 samp/sec. I am sending ~1072 bits each time I write to the Serial Comm (if I'm counting right??) so I should have enough room to increase the amount of bits to send per second (around 3 times what I am currently sending).

**In summary, my two main issues are: if I increase the baud rate, I get garbage in my Serial Comm and if I try to increase my "sampling rate" by decreasing my delays, timing issues appear and my data is split up erroneously. Should I be using a different function, like Serial.flush()?**

**I greatly appreciate any feedback, thank you for your time!**

    // Data acquisition
    // updated  March 30, 2017

    //Note: This version is for TEMPERATURE, HUMIDITY and PRESSURE data
    acquisition ALONE. No motor/conveyor control.

    //***GLOBAL VARIABLES***//

    float lfactor = 125.0;
    float afactor = 1.15;

    /////////////////////////

    //Standard setup with analogReference to 5Volts.

    void setup() {

    Serial.begin(9600);
    }

    void loop() {

    //******THERMOCOUPLES*******//

    //get voltage reading
    // [code]; TC # - Location

    float tcv1 = analogRead(A4) * ( 5.0 / 1024.0 ); //TC 1
    float tcv2 = analogRead(A7) * ( 5.0 / 1024.0 ); //TC 2
    float tcv3 = analogRead(A8) * ( 5.0 / 1024.0 ); //TC 3
    float tcv4 = analogRead(A9) * ( 5.0 / 1024.0 ); //TC 4
    float tcv5 = analogRead(A10) * ( 5.0 / 1024.0 ); //TC 5

    //convert to temperature using custom equation based on 5V reference
    float tc1 = ( 188.7755 * tcv1 ) - 245.3959;
    float tc2 = ( 188.7755 * tcv2 ) - 245.3959;
    float tc3 = ( 188.7755 * tcv3 ) - 245.3959;
    float tc4 = ( 188.7755 * tcv4 ) - 245.3959;
    float tc5 = ( 188.7755 * tcv5 ) - 245.3959;

    //******HUMIDITY SENSORS********//

    float hs1 = ((( analogRead(A13) * ( 5.0 / 1024.0) ) / 5.0 ) * 100.0 ); //HS
    1
    float hs2 = ((( analogRead(A15) * ( 5.0 / 1024.0) ) / 5.0 ) * 100.0 ); //HS
    2

    //******PRESSURE SENSORS********//

    //obtain voltage signal from Sensirion sensor
    float pvolt = analogRead(A0) * (4.995 / 1024.0);

    //convert to Pascals using equation from datasheet, including altitude
    compensation
    //P = lfactor * (voltage[V] - .250 ) / 3.750

    float pressure =  lfactor * ( pvolt - .250 ) / 3.750;
    float pascals = pressure * afactor;

    Serial.print("TC1");
    Serial.print(":");
    Serial.print(tc1);
    Serial.print(";");

    Serial.print("TC2");
    Serial.print(":");
    Serial.print(tc2);
    Serial.print(";");

    Serial.print("TC3");
    Serial.print(":");
    Serial.print(tc3);
    Serial.print(";");

    Serial.print("TC4");
    Serial.print(":");
    Serial.print(tc4);
    Serial.print(";");

    Serial.print("TC5");
    Serial.print(":");
    Serial.print(tc5);
    Serial.print(";");

    Serial.print("RH 1");
    Serial.print(":");
    Serial.print(hs1);
    Serial.print(";");

    Serial.print("RH 2");
    Serial.print(":");
    Serial.print(hs2);
    Serial.print(";");

    Serial.print("Pressure");
    Serial.print(":");
    Serial.print(pascals);
    Serial.print(";");

    Serial.println("");
    delay(1000);

      }

**Python Code:**

    from threading import Thread
    import time
    import serial
    import os
    global datalist
    global fileName

    global motorspeed

    motorspeed = 0

    def serInitialization():
        #activate the serial port, if possible
        try:
            ser = serial.Serial('COM9', 9600) #initialize the serial port
            print "Serial connection successful."
            return ser
        except:
            print "Error: serial port cannot be initialized"
            while(1):
                voidholder = 1

    def getDateTime():
      """Function grabs current time and date, then returns values in a 2-
     element list. """
       timeNow = time.strftime("%H:%M:%S")
       dateToday = time.strftime("%m/%d/%y")
      return [dateToday, timeNow]

    def writetocsv(data):

        """ function writes datalist values to a csv file. If daily csv file
    exists already,
        list values are simply appended to end of file. If it does not, function
    creates the file,
        then appends values.
        """

        global csv_success

        header = ["date", "time", " ", "TC1", " ", "TC2", " ",
    "TC3", " ", "TC4", " ", "TC5", " ", "HS1", " ", "HS2"," ",
    "PRESSURE", " ", "PRESSURE(alt)", "\n"]

        fileName = str(time.strftime("%m_%d_%y_")+ "log.csv")

        if os.path.exists(fileName):
            f = open(fileName, "a")

        else:
            f = open(fileName, "a+")

            for element in header:
                f.write(element + ",")
            f.write("\n")

        for element in data:
            if type(element)==str:
                f.write(element + ",")
            if type(element) == list:
                for i in element:
                    f.write(i + ",")

        f.write("\n")
        f.close()
        csv_success = True

    def mainprogram():

        data = []

        if ser.inWaiting():
            datetimeData = getDateTime()

            for i in datetimeData:
                data.append(i)

            val = ser.readline().strip('\n\r').split(';')
            print "Current readings: "
            for i in range(0,len(val)):
                sensorData = val[i].split(':')
                data.append(sensorData)

                print sensorData

            writetocsv(data)

            time.sleep(1)

            print "\n" * 50

    #Initializes the serial port with the arduino so now we can read what
    Arduino is sending us!
    print "*******************************"
    print "DATA ACQUISITION PROGRAM       "
    print "*******************************"
    print "Data files are saved under "
    print "C:\\Users\\lpaw\\Downloads\\python workspace"
    print "*******************************"

    ser = serInitialization()

    while True:

       mainprogram()

**Screenshots of errors:**
[![Arduino Serial Comm and Python IDLE - data becomes messed up][1]][1]

[![Baud rate error][2]][2]

  [1]: https://i.stack.imgur.com/agYCD.png
  [2]: https://i.stack.imgur.com/jozIB.png

title: Serial Comm. timing issue between Arduino and Pyserial

Answers: 3

body:
You certainly should use a single Serial.flush at the end of your loop()

    Serial.println("");
    Serial.flush()
    delay(100);

Remember you have limited SRAM to store characters.
I'd suggest you should use the inbuilt serial monitor in the Arduino IDE with the above alteration, and increase your baud rate. There should be no problems sending data at 115k baud.

You should also consider sending a signal back from Python that you have received a valid reading string (ACK/NAK) that way you can remove delays altogether (you still need the flush).

body:
Your main problem is in erroneously having a delay in both the sender and the receiver.  While this sometimes works by lucky accident, it essentially never does what is hoped for by those who try it.

In a system such as this, you should have a delay in the sender only, in order to produce quasi-regular sample intervals, but no delay in the receiver.  Rather, the receiver should accept data whenever the transmitter produces it, or more specifically in your case, every time it completes a terminated line of data.

But you also seem to want to write the data in an organized way as sets of measurements.  To do that, you should reject data until you see the first "TC1", then collect lines to fill in a data block until and end of data condition is recognized (in your case a blank line), and write it out to disk in a timestamped file.  You may also want to include code that abandons a corrupted block unwritten if any of the intermediate reading headers aren't as expected, and goes back to looking for the next hopefully clean TC1, or marks it as erroneous, or whatever.

To use a different baud rate, you must apply a matching setting in both the Arduino and the python ends of the link.

Also note that while the Arduino serial monitor is indeed useful for debugging, you *must not* have it open while trying to collect data with python - this will either cause an error in that one program is disallowed, or the two programs to fight over the data and each get incomplete results.

Another technique which can be simple and useful, especially during development, is to write every received line of serial data out to a text file with a numeric timestamp at the start of each line.  You can then have a second process which reads this file, grabs complete multi-line records, and writes them out using either the timestamp of the first or last element of the record.  In particular this lets you get an intermediate view of the data to understand any oddities.  With various Unix style command line tricks you can even run the first program both saving the intermediate format and feeding the second record extraction program in real time.

body:
Does your Python code have any way of determining the start & end of a data set?
Does it 'assume' that when it reads a chunk of data from the serial port that the first byte it gets will always be the start of a "Cond.temp" and the last byte will be the ; at the end of Press(alt)?
After reading a chunk of data, do you have any check to see if it is complete or if you should wait a few 10's of milliseconds and go back to read some more?

I'm assuming the answers to these questions are No, Yes & No.

Your PC and your Arduino are running completely asynchronously - neither one really knows what the other is doing.
When your python code reads a chunk of data from the serial port (I'm making another assumption here - that you're not reading it byte-by-byte), you have no way of knowing that the beginning of that chunk is really the beginning of your data set.
Similarly, you also have no way of knowing that the end of that chunk is the end of your data set - maybe it's only a small piece - or maybe you're getting the beginning of the next set glued to the end of this on.

If you're using a USB-Serial adapter then your data is even more likely to arrive in bits & pieces which you'll need to reassemble - just by the nature of how these beasties often work - they could be buffering some number of serial bytes before packaging them together in a single USB packet.

You need some way of flagging the start and/or end of your data sets. Even something as simple as a \n newline character at the end of each one might work for you.
Then, you need to read in *and buffer* the data you're receiving *until you know you've reached the end of a data set*.
So, for the \n example:
 - read some stuff
 - add it to a buffer
 - do you have a \n *anywhere in the buffer*?
 -- yes - pull that section from the start of the buffer up to the \n & process it
 -- no - go back to the beginning and wait for more stuff
 - after you've pulled some stuff out of the buffer to process,
   *don't just forget the rest - it could be the start of your next data set!*
 - move it to the start of your buffer
 - rinse & repeat

For your baud-rate issue I can't say much for sure. The garbage you're seeing is typical for a mismatched baud-rate situation.
Check that your particular Arduino supports the baud rates you're trying to use at whatever clock speed you're running it at.
Check that your USB-Serial adapter (if you're using one) works at those speeds (either loop pins 2&3 and type to yourself in a terminal or get another, preferably different one, and hook them together with a 3-wire link pin 2-3, pin 3-2, pin 5-5).


body:
I tried a simple blink for my fingerprint sensor which is GT-511C1R, but I have experienced of having an error.

>FPS_Blink.ino:12:26: fatal error: FPS_GT511C1R.h: No such file or directory
compilation terminated.

I downloaded the whole library but still same error.

Answers: 1

body: Please learn how to install a library from [here](https://learn.sparkfun.com/tutorials/installing-an-arduino-library). And see if error is coming or not.


body:
I want to make a temperature data logger by using Arduino.

I can read a data every 1sec and I want to store 30days data with date&Time.

In data logger, I want to write a temperature data with date&time in the .csv file and this file will be generated after I attaching USB.

So, Please suggest me Arduino board with USB compatible(working on 3V battery) and also suggest me EEPROM who able to store 30 days data.

title: Suggest me Arduino device with USB for Mass storage

Answers: 2

body:
60 samples per minute, 60 minutes per hour, 24 hours per day, 30 days - that's 2592000 samples. At 10 bytes per sample (a very generous allocation) that's less than 30MB of data.

You could fit that many many times over on even the smallest of today's SD cards, so why mess with the complexity of USB? *Any* Arduino can work with an SD card.

A bigger concern of yours should not be the storage medium, which is trivial - you should instead be thinking about *how you will run the board off a 3V battery for 30 days*.

body:
Despite your poor written question, I'll reply to you with a code, I used in my temperature logger 2 weeks ago. Includes LCD, temp sensor and SD card.

Delay is set for 9,1s which sums up with the calculation times of Arduino to 10 +/- 0.05 sec.
Lower it down to 100ms, if you want to be written every 1 second.

PS: The lower row, most right: There is a sign in letters, the condition of the sistem.

N = something's wrong, not inserted card/not connected SD card module
O = everything's okay, it's data logging

    #include <OneWire.h>
    #include <DallasTemperature.h>
    #include <LiquidCrystal.h>
    #include <SPI.h>
    #include <SD.h>
    #define ONE_WIRE_BUS 6 OneWire oneWire(ONE_WIRE_BUS); DallasTemperature sensors(&oneWire); LiquidCrystal lcd(8, 7, 5, 4, 3, 2);

    const int chipSelect = 10;

    void setup() {

      Serial.begin(9600);   Serial.println("Arduino Digital Temperature // Serial Monitor Version");   sensors.begin();
         lcd.begin(16, 2);   lcd.setCursor(0, 0);   lcd.print("Temperatura:");   //*********************************************
        while (!Serial) {   }   lcd.setCursor(15, 1);   lcd.print("??");   Serial.print("??");

      if (!SD.begin(chipSelect)) {
        Serial.println("NO");
          lcd.setCursor(15, 1);
          lcd.print("NO");
        return;   }   else   {   lcd.setCursor(15, 1);   lcd.print("OK");   Serial.println("OK");   }   //********************************************* }

    void loop() {

      String dataString = "";

      float abc;

      sensors.requestTemperatures();     Serial.print("Temperature is: "); Serial.println(sensors.getTempCByIndex(0));   lcd.setCursor(0, 1);   lcd.print(sensors.getTempCByIndex(0));

      File dataFile = SD.open("datalog.txt", FILE_WRITE);

        if (dataFile) {
        dataFile.println(sensors.getTempCByIndex(0));
        dataFile.close();    Serial.println(sensors.getTempCByIndex(0));
        }
           else {
        Serial.println("error opening datalog.txt");   }

      //delay(9100);    }


body:
I am new to Arduino.

My project is an electronic piano that has 8 tactile switch keys that can play 8 octaves. I want to record a song that a user plays on the keys into EEPROM. I have implemented it. However, the playback is bad. You can't hear different note frequencies but you can hear soft buzzing when a note is supposed to be played.

Here is my code. Could you please help me find the problem? Thank you in advance.

    #include <EEPROM.h>
    #include "pitches.h"
    #define speaker A5
    #define record_button 3
    #define play_button 5
    #define record_led 2
    #define play_led 4

    int eeAddress = 0;
    int eeAddressplay = 0;
    const int inPot = A1; // potentiometer to change octaves (8 octaves total)
    byte octave;
    byte tone_out;
    int tone_key; // frequency of key
    boolean silence;
    int maxNumber = 500;
    byte time = 20;
    byte check = 0;
    byte buttons[] = {6,7,8,9,10,11,12,13};
    int saveSounds[500];
    int saveNumber = 0;

    byte melody1[8] = {
      NOTE_C1 , NOTE_D1, NOTE_E1, NOTE_F1, NOTE_G1, NOTE_A1, NOTE_B1, NOTE_C2};
    byte melody2[8] = {
      NOTE_C2 , NOTE_D2, NOTE_E2, NOTE_F2, NOTE_G2, NOTE_A2, NOTE_B2, NOTE_C3};
    int melody3[8] = {
      NOTE_C3 , NOTE_D3, NOTE_E3, NOTE_F3, NOTE_G3, NOTE_A3, NOTE_B3, NOTE_C4};
    int melody4[8] = {
      NOTE_C4 , NOTE_D4, NOTE_E4, NOTE_F4, NOTE_G4, NOTE_A4, NOTE_B4, NOTE_C5};
    int melody5[8] = {
      NOTE_C5 , NOTE_D5, NOTE_E5, NOTE_F5, NOTE_G5, NOTE_A5, NOTE_B5, NOTE_C6};
    int melody6[8] = {
      NOTE_C6 , NOTE_D6, NOTE_E6, NOTE_F6, NOTE_G6, NOTE_A6, NOTE_B6, NOTE_C7};
    int melody7[8] = {
      NOTE_C7 , NOTE_D7, NOTE_E7, NOTE_F7, NOTE_G7, NOTE_A7, NOTE_B7, NOTE_C8};

    //PIANO FUNCTION
    void freePlay()
    {
      octave = map(analogRead(inPot),0,1023,1,7);
      if (digitalRead(buttons[0]) == HIGH) {
        tone_out = 0;
        silence = false;
      }
      else if (digitalRead(buttons[1]) == HIGH) {
        tone_out = 1;
        silence = false;
      }
      else if (digitalRead(buttons[2]) == HIGH) {
        tone_out = 2;
        silence = false;
      }
      else if (digitalRead(buttons[3]) == HIGH) {
        tone_out = 3;
        silence = false;
      }
      else if (digitalRead(buttons[4]) == HIGH) {
        tone_out = 4;
        silence = false;
      }
      else if (digitalRead(buttons[5]) == HIGH) {
        tone_out = 5;
        silence = false;
      }
      else if (digitalRead(buttons[6]) == HIGH) {
        tone_out = 6;
        silence = false;
      }
      else if (digitalRead(buttons[7]) == HIGH) {
        tone_out = 7;
        silence = false;
      }
      else {
        silence = true;
      }

      if (silence == false)
      {
        switch(octave)
        {
        case 1:
          tone_key = melody1[tone_out]; break;
        case 2:
          tone_key = melody2[tone_out]; break;
        case 3:
          tone_key = melody3[tone_out]; break;
        case 4:
          tone_key = melody4[tone_out]; break;
        case 5:
          tone_key = melody5[tone_out]; break;
        case 6:
          tone_key = melody6[tone_out]; break;
        case 7:
          tone_key = melody7[tone_out]; break;
        }
        tone(speaker,tone_key);
      }
      else {
       noTone(speaker);
       delay (5); }
    }

    //SETUP FUNCTION
    void setup()
    {
     for(int i = 0; i < 8; i++)
     {
      pinMode(buttons[i], INPUT);
     }
     pinMode(speaker, OUTPUT);
     pinMode(melody_button, INPUT);
     pinMode(record_led, OUTPUT);
     pinMode(play_led, OUTPUT);
     pinMode(inPot, INPUT);
    }

    //MAIN CODE
    void loop() {
    freePlay();
    if (digitalRead(record_button) == HIGH) {
      digitalWrite(record_led, HIGH);
        for(int i = 0; i < maxNumber ; i++) {
          octave = map(analogRead(inPot),0,1023,1,7);
            if (digitalRead(buttons[0]) == HIGH) {
            tone_out = 0;
            silence = false;
            }
            else if (digitalRead(buttons[1]) == HIGH) {
            one_out = 1;
            silence = false;
            }
            else if (digitalRead(buttons[2]) == HIGH) {
            tone_out = 2;
            silence = false;
            }
            else if (digitalRead(buttons[3]) == HIGH) {
            tone_out = 3;
            silence = false;
            }
            else if (digitalRead(buttons[4]) == HIGH) {
            tone_out = 4;
            silence = false;
            }
            else if (digitalRead(buttons[5]) == HIGH) {
            tone_out = 5;
            silence = false;
            }
            else if (digitalRead(buttons[6]) == HIGH) {
            tone_out = 6;
            silence = false;
            }
            else if (digitalRead(buttons[7]) == HIGH) {
            tone_out = 7;
            silence = false;
            }
            else {
            silence = true;
            tone_key = 0;
            }

            if (silence == false) {
            switch(octave) {
            case 1: tone_key = melody1[tone_out]; break;
            case 2: tone_key = melody2[tone_out]; break;
            case 3: tone_key = melody3[tone_out]; break;
            case 4: tone_key = melody4[tone_out]; break;
            case 5: tone_key = melody5[tone_out]; break;
            case 6: tone_key = melody6[tone_out]; break;
            case 7: tone_key = melody7[tone_out]; break;
            }
            tone(speaker,tone_key);
            delay(time);
            }
            else {
            noTone(speaker);
            tone_key = 0;
            delay (time);
            }

        saveSounds[saveNumber] = tone_key;
        saveNumber++;
        if (digitalRead(play_button) == HIGH){
        break;}
        }

    digitalWrite(record_led, LOW);
    tone(speaker, 700);
    delay(200);
    noTone(speaker);
    check++;
    }

    for (int i = 0; i<500; i++) {
      EEPROM.put(eeAddress,saveSounds[i]);
      eeAddress = eeAddress + 2;
    }

    if(check >= 1) {
      while (0 == 0){
        freePlay();
        if(digitalRead(play_button) == HIGH) {
          digitalWrite(play_led, HIGH);
            for(int i = 0; i < maxNumber; i++) {
            if(saveSounds[i] != 0) {
              tone(speaker,EEPROM.get(eeAddressplay,saveSounds[i]));
              eeAddressplay = eeAddressplay + 2;
              delay(25);
            }
            else {
              noTone(speaker);
              delay(time);
            }
            }
          noTone(speaker);
          digitalWrite(play_led,LOW);
        }
        freePlay();
      }
    }
    }

title: EEPROM PUT and GET audio playback

Answers: 1

body:
NOTE: this is not an answer, but a response not able to put in a comment as request from the submittor mirandamg.

For the first example

Instead of

    if (digitalRead(buttons[0]) == HIGH) {
      tone_out = 0;
      silence = false;
    }
    else if (digitalRead(buttons[1]) == HIGH) {
      tone_out = 1;
      silence = false;
    }
    ...

Use

    for (int buttonIndex = 0; buttonIndex < 8; buttonIndex++)
    {
        if (digitalRead(buttons[butonIndex] == HIGH)
        {
           tone_out = buttonIndex;
           silence = false;
        }
    }

This method does not work directly for variables melody1, 2, 3...
Therefore, make an array, instead of:

    byte melody1[8] = {
    ...

use

    byte melodies[8][8] = {
    ...

The first 8 is for the number of melodies, the second is for the number of notes.

You can improve it even further by making 2 constants:

    const byte NR_OF_MELODIES = 8; // Number of melodies
    const byte NR_OF_NOTES = 8;    // Number of notes per melody

And the array can be created s

    byte melodies[NR_OF_MELODIES][NR_OF_NOTES] = {

If you make a const for the number of buttons:

    const byte NR_OF_BUTTONS = 8; // Number of physical buttons

Then also the first line in the loop in my example can be changed as:

    for (int buttonIndex = 0; buttonIndex < NR_OF_BUTTONS; buttonIndex++)

If you later need to change the number of notes, melodies or buttons, you don't need to iterate over your application to find all values. Especially since they are all 8.


body:
I want to save different values on address 0 and 1 on eeprom I tried to change it but when I put data on address 0 and also put data on address 1 the address 0 change its value stored into random number and vice versa .. Is it possible to change the value of respective address without affecting others ..

**CODE**

    in the setup
         int eepromSize=EEPROM.length();
          Serial.print("EEPROM found, size=");
          Serial.println(eepromSize);
            // Get the last fade value (as an integer)
          EEPROM.get(0, WATEREQFORN1);
          Serial.print("Last Value N1: ");
          Serial.println(WATEREQFORN1);

          EEPROM.get(1, WATEREQFORN2);
          Serial.print("Last Value N2: ");
          Serial.println(WATEREQFORN2);

The user will input the value that will be save in eeprom i use switch because the user will input like this example .. 100A or 23B

    case 'A':
            Serial.print("Case A got ");
            Serial.println(val);
            WATEREQFORN1 = val;

                EEPROM.put(0, WATEREQFORN1);
                Serial.print("DATA SAVE TO EEPROM");

            break;
          case 'B':
            Serial.print("Case B got ");
            Serial.println(val);
             WATEREQFORN2 = val;
             EEPROM.put(1, WATEREQFORN2);
             Serial.print("DATA SAVE TO EEPROM");

            break;

The problem is, when I change/write value into address 0 and after that change/write also into address 1 the value on address 0 also change into different random numbers.

title: Is it possible to save different values on address 0 and 1 in EEPROM?

Answers: 4

body:
Probably WATEREQFORN1 is an int or word, at least more than one byte.

If you write a 2 byte value on address 0, it will occupy address 0 and 1.

When you overwrite address 1 (again with a 2 byte value), it will occupy addres 2 and 3, destroying the LSB part of the value written to byte 0.

Try writing on address 0 and 2 (or 0 and 4 when using 4 bytes).

body:
EEPROM.put() and EEPROM.get() write or read the object you pass them. An `int` is 2 bytes so that is what they write or read. It sounds like you intended for the functions to only handle 1 byte. In that case, make the your variable's data type something that is 1 byte, such as `int8_t`; otherwise allocate 2 bytes of EEPROM to each.

Update:
It works because you had only allocated 1 byte in EEPROM for each variable but you store 2-byte variables. Now you're storing 1-byte variables, which matches your EEPROM allocation.

body:
The variable names in all upper case is a style problem you should address.  Conventionally, C and C++ programmers use all-upper-case names to designate defined constants or macros.  Contravening that convention can lead to confusion if other people use or maintain the code.  Instead of `WATEREQFORN1` consider `waterEq1`, etc.

The problem of your second value overwriting part of the first in EEPROM is an allocation problem.  Presumably the `WATEREQ...` variables are multiple bytes in length.  `EEPROM.get()` and `put()` read and write data types with multiple bytes using several consecutive bytes of EEPROM.  For example, if `WATEREQFORN1` is a real and takes 4 bytes, it will occupy cells 0, 1, 2, 3 in EEPROM.

The following code snippet shows a way to automatically and systematically allocate EEPROM space.  The `sizeof` operator returns the size in bytes of its argument.  Thus, an expression like `WaterAddr2=WaterAddr1+sizeof waterEq1` correctly sets `WaterAddr2` to be the next available cell after `waterEq1`, no matter what type `waterEq1` is.

    enum { WaterAddr1=0, WaterAddr2=WaterAddr1+sizeof waterEq1, DelayAddr=WaterAddr2+sizeof waterEq2 };
    ...
    case 'A':
      waterEq1 = val;
      EEPROM.put(WaterAddr1, waterEq1);
      break;
    case 'B':
      waterEq2 = val;
      EEPROM.put(WaterAddr2, waterEq2);
      break;
    case 'D':
      Delay = val;
      EEPROM.put(DelayAddr, Delay);
      break;
      ...

body:
> Is it possible to change the value of respective address without affecting others ..

Yes, if the two values are 8-bit types.

Otherwise, No.


body:
Good morning,

I would like to use an Arduino Duemilanove to read the voltage signal generated from a current sensor (CSLA2CD). The datasheet for this sensor can be found [here](http://www.scienceshareware.com/articles/measuring-current/csla2cd-current-sensor.pdf).

The problem is that the sensor requires a supply voltage of 6 to 12v. The signal output voltage is half the supply when no current flows through the sensor. I am using a 8v regulator for its supply, so the signal voltage may range from 4v (no current sensed) all the way to about 6v (about 60 amps).

Unless I'm mistaken, the arduino's analog pin can detect from 0v to 5v. So it would only accurately provide me data up to the 5v signal mark.

My questions are:

 1. Would a voltage divider be a good solution to reduce the signal voltage to a range the Arduino can read? If so,

 2. what would be the best resistor combination to use?

If there are better solutions than a voltage divider then please share.

Thanks very much!

title: Using voltage divider to read voltage from sensor

Answers: 1

body:
It should work, but I don't know if its the best way.

Because the maximum voltage is 12 volts (I know you are only giving it 8, but you don't want to fry your board) you need the divider to send the Arduino 5/12 of the power.  You don't need much current, so you can use big values or resistors.  10K and 24K should work, but you should research or test this before you hook it up to you kit.


body:
I am using some sensors with the arduino which take a second to receive the data from them. My guess is that there is a delay used somewhere in the library. During this time the multiplexed displays stop working as the rapidly changing grounds are temporarily paused and only one of the displays has the digit lit up. I could change the sensor I'm using (DHT11) to something I could AnalogRead, however I'm curious if there is an external IC for this which drives multiplexed displays with some sort of serial communication or I2C between the arduino and it. I could use a separate arduino(or ATTiny) and write some code for it to do this, but is there a class of chips which already do this? Something where you could pass bytes of the digits and the multiplex delay and it continues to multiplex until the next data is received.

I don't mind if in this time the digits are left in their last states similar to how it would operate if they were directly driven rather than multiplexed. If anyone has insight that would be great!

title: Multiplex 7 segment during delay (external IC?)

Answers: 1

body:
Perhaps a [MAX7219][1] would do what you want.

> The MAX7219CNG+ is a 8-digit serially interfaced LED Display Driver for LED matrix displays.
> The MAX7219 is compact, serial input/output common-cathode display drivers that interface microprocessors (¦ÌPs) to 7-segment numeric LED displays of up to 8 digits, bar-graph displays or 64 individual LEDs.
Included on-chip are a BCD code-B decoder, multiplex scan circuitry, segment and digit drivers and an 8x8 static RAM that stores each digit.
Only one external resistor is required to set the segment current for all LEDs.
A convenient 4-wire serial interface connects to all common ¦ÌPs.
Individual digits may be addressed and updated without rewriting the entire display.
> The MAX7219 also allow the user to select code-B decoding or no-decode for each digit.

  [1]: http://playground.arduino.cc/Main/MAX72XXHardware


body:
I want to learn more about the shiftout function used with Arduinos and used the implementation with my ATMEGA328p.

**The Setup**

This is the original `shiftout` function used in Arduino Programming, except that I replaced 1 with HIGH.

    #define F_CPU 1000000UL
    #define BAUD 9600UL
    #define LSBFIRST 0
    #define MSBFIRST 1
    #define HIGH 0x1
    #define LOW  0x0
    #define INPUT 0x0
    #define OUTPUT 0x1

    #include <avr/io.h>
    #include <util/delay.h>
    #include <USART.h>
    #include <pinDefines.h>

    #define DATA PD7
    #define LATCH PB2
    #define CLOCK PB0

    void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
    {
     uint8_t i;
     for (i = 0; i < 8; ++i) {
      if (bitOrder == LSBFIRST) {
       PORTD |= (!!(val & (HIGH << i)) << DATA);
       } else {
       PORTD |= (!!(val & (HIGH << (7 - i))) << DATA);
      }
      PORTB |= (HIGH << clockPin);
      PORTB &= ~(HIGH << clockPin);
      }
    }

**Main**

    int main(void)
    {
     initUSART();
     DDRD |= (HIGH << DATA);
     DDRB |= (HIGH << LATCH) && (HIGH << CLOCK);

     PORTB |= (HIGH << LATCH);
     shiftOut(DATA, CLOCK, LSBFIRST, 1);
     printBinaryByte(PIND);
     PORTB ^= (HIGH << LATCH);

        /* Replace with your application code */
        while (1)
        {

        }

     return (0);
    }

I created an example to understand more about the function, but the outcome does not add up to what I expected to see.

**Szenario**

    PORTD |= (!!(val & (HIGH << 0)) << DATA);

This is what I expect for `val = 1`

 - `(HIGH << 0)` = `00000001`
 - `val & (HIGH << 0)` = `00000001 & 00000001`
 - `!!(val & (HIGH << 0))` = `1`
 - `PORTD |= (1 << DATA)`

As `PORTD` is the data pin on the shift register, it should get `00000001`.
When I print the binary number within `PORTD` I get: `10000111` and my LED Array connected to the 74HC595 displays: `10101111`

I am really lost.... I checked the connections to the LEDs and they are all good. Can you explain to me why I receive this awkward result?

title: Shift Register on ATMEGA328p

Answers: 3

body:
That is some ugly and needlessly slow code!

Nonetheless, I think the main point you need to keep in mind is that when you `OR` the value `00000001` into `PORTD`, you are *only* changing the bottom bit to a `1` - all other bits will be left untouched to whatever value they already had.

So, it seems that `PORTD` had the value of either `10000111` or `10000110` before you executed `PORTD |= (1 << DATA)` (which is the equivalent of `PORTD |= 0b00000001`)....

       10000110
    OR 00000001
    ===========
       10000111

The output of your shift register is also just an artifact of whatever the most recent series of bits that you sent to it was. Each time you send a new bit, whatever was there will get shifted over and only the single new bit will be shifted in.

Make sense now?

body:
> This is what I expect for val = 1
>
> PORTD |= (1 << DATA)
> As PORTD is the data pin on the shift register, it should get 00000001.

your deduction is correct and the code is correct -> remember this is the case for LSBFIRST. so "val = 0x01" should be sent out as "0b1000 0000", which is precisely what the code is doing.

> !!(val & (HIGH << 0))

the "!!" operator is often used to turn a logic value into either '1' or '0'.

the code for shiftout() can be greatly improved.

body:
First of all, PORTD represents the current output state of 8 physical GPIO pins (I think some devices have fewer pins on a port but usually there's 8).  I think what you're trying to do is shift a sequence out of a single pin. So just reading it will only tell you what each of the 8 pin states are at that moment, not what you shifted out.  I think Arduino's way of doing things is actually harder than just writing the plain C code so I'll ignore it (what is the '!!' ???).

So taking a step back, here's code for pushing an 8bit number serially out of a pin:

    uint8_t serialData = 0b10011101;  // random data to shift out
    uint8_t pin = 3;                  // the pin on PORTD we want to toggle

    uint8_t i;
    uint8_t nextBit;
    for (i = 0; i < 8; i++) {

      // Find the nextBit value to set by shifting our input data by our index
      //   and clearing the other values.  E.g. if serialData == 0b10011101 and
      //   i == 2 then (0b10011101 >> 2) == 0b00100111.  0b00100111 & 1 == 1
      nextBit = (serialData >> i) & 0b00000001;

      // If the next bit is a one, we "or" it to set it
      if (nextBit) {
        // The 'or' operator can only set bits to 1
        PORTD |= 1 << pin;        // in this case, (1 << 3) == 0b00001000
      } else {
        // The 'and' operator can only clear bits to 0
        PORTD &= ~(1 << pin);    // in this case, ~(1 << 3) == 0b11110111
      }
    }

If you want to add a "clock" pin to go along with the data (like the arduino code) then you can set the clock pin to whatever state before the "for" loop then use an "xor" operator to toggle it each time through the loop:

    clockPin = 4;

    // just before the 'for' loop set the clock to whatever starting state you
    //   want.  In this case I'll start it at 0.
    PORTB &= ~(1 << clockPin);
    .
    .
    .
    // Now in the 'for' loop (at the bottom for example)
    PORTB ^= (1 << clockPin);

If you want the clock to toggle up then down in a sing loop cycle then you can just repeat the 'xor' twice in a row or force the state using 'or' and 'and' operators.  Also, pay attention to timing, you might be toggling things too quickly if the microcontroller clock is fast.  You can add delays to the loop to shape the timing of the pattern.


body:
I have programmed an ESP8266 using the circuit and program below. I tried to open the SerialMonitor once the program is uploaded to the ESP8266. I am getting an error when I am trying to open the SerialMonitor.

> Error opening serial port 'COM5'. (Incorrect serial port)

What is the way to get the IP address assigned to the ESP8266?

    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>

    //SSID and Password of your wifi router
    const char* ssid = "Moto";
    const char* password = "reset1234";

    ESP8266WebServer server(80);

    void setup() {
      Serial.begin(9600);
      WiFi.begin(ssid, password); //Connect to your WiFi router
      Serial.println("");
      // Wait for connection
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      //If connection successful show IP address in serial monitor
      Serial.println("");
      Serial.print("Connected to ");
      Serial.println(ssid);
      Serial.print("IP address: ");
      Serial.println(WiFi.localIP());  //IP address assigned to your ESP
      server.begin(); //Start server
      Serial.println("HTTP server started");
    }

    void loop() {
      server.handleClient(); //Handle client requests
    }

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

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

  [1]: https://i.stack.imgur.com/BzYbU.jpg
  [2]: https://i.stack.imgur.com/wbfgI.png

title: How do I know the IP address assigned to an ESP8266?

Answers: 2

body:
If you give your board a name with

    WiFi.hostname("MyESP8266");

(for example) you can then look on your router in the section that lists DHCP assignments (on my Netgear it's *Attached Devices*). That should then show you the IP address of all the attached devices, including the ESP8266 which you will easily identify by its name.

Another option is to use mDNS. Look at some of the examples that come with the ESP8266 core and libraries to see how.

body: I used the app "Fing" on my phone. It shows you the devices that are connected to your WiFi. After entering all freacking IP adress aviable, found that the last one was the one of my esp8266 and a beautiful window saying "hello from esp8266!" appeared.


body:
we're trying to add some code to the SparkFun Blynk Board. We don't want to overwrite the firmware, because that allows it to work with the iphone app, but we need to add our own voids and Blynk. Write commands in order to control this servo RC car via wifi wit the Joystick XY. any ideas?

our code:

    #include <Servo.h>
    #include <SPI.h>
    #include <ESP8266WiFi.h>
    #include <BlynkSimpleEsp8266.h>
    #include <Adafruit_NeoPixel.h>
    #include <SoftwareSerial.h>
    //#define BLYNK_PRINT Serial

    char BlynkAuth[] = "6dfb81c116d84003a505056239c23559";
    char ssid[] = "Linksys23266";
    char pass[] = "roboboyz";

    Servo servoR;
    Servo servoL;

    int pos = 90;

    void forward()
    {
      servoR.write(110);
      servoL.write(110);
    }

    void turnRight()
    {
      servoR.write(80);
      servoL.write(90);
      delay (2000);
    }

    void turnLeft()
    {
      servoR.write(90);
      servoL.write(80);
      delay(2000);
    }

    void reverse()
    {
      servoR.write(70);
      servoL.write(70);
      delay(2000);
    }

    void Stop()
    {
      servoR.write(94);
      servoL.write(94);
      delay(2000);
    }

    void setup()
    {
      Blynk.begin(BlynkAuth, ssid, pass);  // wifi username and password
      servoR.attach(12);
      servoL.attach(13);
      Serial.begin(9600);
      delay(1000);
    }

    BLYNK_WRITE(V1)
    {
      int x = param[0].asInt();
      int y = param[1].asInt();

      // Do something with x and y
      Serial.print("X = ");
      Serial.print(x);
      Serial.print("; Y = ");
      Serial.println(y);
      if(y>220)
      forward();
      else if(y<35)
      reverse();
      else if(x>220)
      turnRight();
      else if(x<35)
      turnLeft();
      else
      Stop();
    }

    void loop()
    {
      Blynk.run();
    }

title: loading custom code onto SparkFun Blynk Board

Answers: 1

body:
That's not how microcontrollers work. You have one firmware and only one firmware. When you upload firmware you replace the existing firmware. You cannot "add" to it.

Instead you will have to write a new firmware that contains *all* the code you need to do the *entire* job.


body:
I am trying to use a WeMos module to send a broadcast message through an peer-to-peer network (Ad-Hoc). The thing is that i can't give a SSID nor Password to that network, i just can define it through them IP Addresses. As you suspect i don't have a specific idea of the configuration of the Wemos module.

**What am I talking about?**

I need to receive messages in a IEEE802.11 software-defined radio module. In this module I can't establish a network, just listen to a channel, and read whatever someone is sending. Think about it as a sniffer. But in this case i can assign to this module a MAC and IP within the Network.

**What do I need?**

I need just to:

    Initialize peer-to-peer (Ad Hoc) network without an SSID nor Password.
    Set a channel (I do it with channel 13, it is most times free).
    Send a broadcast message in that channel to the SDR module in the network.

**In other words**
Module SDR:
 - IP:192.168.123.2
 - MAC: xxx
Wemos
 - IP:192.168.123.3
 - MAC: xxx

Through Wemos:

 - wifi, send broadcast message

The mask is /24, then it is going to send the message to all IPs from 192.168.123.2 to 192.168.123.254, then, for sure to the SDR Module, and i could receive it.

Thanks in advance.

Best regards,

Cristian

title: Wifi proof with WeMos D1 ESP8266 Ad-Hoc

Answers: 1

body: ESP8266 does not currently support Ad-Hoc/IBSS mode.


body:
I'm trying to make a speedometer, with utilization of interrupt for get number of pulse and some calculation for getting speed, but when compute speed the arduino freeze for some second and i lose alot of impulse and false all my successive capture of impulse. Why? thanks for reply

    const int contaImpulsi = 2;
    volatile int impulsi =  0;
    int impulsiOld = 0;
    static int appoggio = 0;
    unsigned deltaT[3];
    unsigned vel = 0;

    void setup() {
      Serial.begin(9600);
      attachInterrupt(contaImpulsi, definisciTempi, RISING);
    }

    void loop() {

      if (impulsiOld == impulsi || impulsi > impulsiOld)
      {
        if (appoggio == 3) {
          deltaT[3] = millis();
          appoggio = 0;
        }
        if (appoggio == 2) {
          //Serial.println("ASSEGNO DELTA T 2");
          deltaT[2] = millis();
          //Serial.println(deltaT[2]);
          appoggio = 3;
        }
        if (appoggio == 1) {
          //Serial.println("ASSEGNO DELTA T 1");
          deltaT[1] = millis();
          appoggio = 2;
        }
        if (appoggio == 0) {
          //Serial.println("ASSEGNO DELTA T 0");
          deltaT[0] = millis();
          appoggio = 1;
        }
      }
      impulsiOld = impulsi;

      if (appoggio == 3) {

        int t1 = (deltaT[1] - deltaT[0]);
        int t2 = (deltaT[2] - deltaT[1]);
        int dividi = t1 + t2;
        vel = (((690 * 2000 / dividi) * 3.6) / 10) * 0.85; // here i think is where the program freeze

        Serial.println("------------------------------------------");
        Serial.print("SPEED: ");
        Serial.println(vel);
        Serial.println("------------------------------------------");
      }
    }

    void definisciTempi() {
      impulsi++;
    }

title: Speedometer slow reaction arduino

Answers: 1

body:
First off a comment on your variable types. It's not the cause of your problem, but just something to watch for in future:

    int impulsi =  0;

This should be voltatile (Edit: I see you updated that, that's ok).

    unsigned deltaT[3];
    unsigned vel = 0;

These lack a type. As such the default to `int`. Your deltaT array should be `unsigned long` since it stores time. It will overflow very rapidly otherwise.

Now on to your problem.

The core of your problem is your methodology of calculating the speed. This bit:

    if (impulsiOld == impulsi || impulsi > impulsiOld)
    {
      ...
    }
    impulsiOld = impulsi;

is going to be running pretty much always. That's because `impulsiOld` and `impulsi` will either always be the same (since you set them to be the same) or `impulsi` is going to be greater than `impilsiOld` since you received a pulse in the brief interlude when it's not running that bit.

And that means that all your `deltaT` entries are going to be the same most of the time.  Which leads me on to the next bit:

    int t1 = (deltaT[1] - deltaT[0]);
    int t2 = (deltaT[2] - deltaT[1]);
    int dividi = t1 + t2;
    vel = (((690 * 2000 / dividi) * 3.6) / 10) * 0.85;

If `delatT[1]` and `deltaT[0]` are the same, then `t1` will be `0`. The same goes for `t2`. `0 + 0 = 0`, so `dividi` will also be 0.

And that means:

    690 * 2000 / 0

Which will be a *divide by zero exception* and will cause the MCU either to lock up or to reboot. If the latter you will see the bootloader run for a couple of seconds.

There are two normal methods of calculating the speed from pulses, and I am not sure what your method is trying to be.

The simplest one is to just count the number of pulses over a given period. Increment the count in your ISR, and after a second has elapsed (or longer, or shorter, depending on the frequencies you are working with) you reset the count to 0 (after storing it elsewhere) and calculate the speed from that stored count.

The other way is to just take the time between two successive pulses. You can average it, maybe with a rolling (AKA moving) average, or just take the raw value depending on what you are measuring.  This method is a little harder since you need to do more work per pulse.

The two methods differ in critical ways when it comes to outputting the results. The first method will always give you a value every second (or whatever time period you use), but it can't cope with pulses that are further apart than the time period you use. The second method doesn't much care about the time between the pulses, but you can only get a meaningful reading if a pulse arrives, which if that is a while means you get no reading for a while. It's harder to determine "not moving" from that.

Also you should look at the use of *critical sections* when accessing your `impulsi` variable outside the interrupt routine. It more than 8 bits, so all access to it will be *non-atomic* and could be interrupted by the ISR.


body:
I am new to the use of Arduino in general, and to the INA226 Module for power metering.

I first got everything set up WITHOUT anything plugged to the INA226 module metering pins (V+, ISens+, Isens-, V- not connected to any power source) and running a sample code that gets data being read by the INA226, of course, all values return 0, but at least I know the program runs and the arduino can connect to the INA226. Now, the problem comes when I try to get some reading such as 5V or even 3.3V from the Arduino pins.

I connected the circuit as follows:

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

<!-- End schematic -->

(I noticed that I wrote A6 instead of A4, sorry about that)

But when I do this, there is no reading at all from the serial console. I tried connecting the V+ and Isens+ directly to the 5V pin leaving everything else as shown in the diagram, but the Arduino board doesn't even turn on.

I tried referencing other sources, but their tests use external power supplies or other equipment I don't have.

I would be really thankful if someone could lend me a hand here or help me understand why am I having this problem and how can I make it read something basic such as 5V or 3.3V directly from the Arduino board.

Thanks!

title: Problem with Arduino and INA226 power meter module

Answers: 2

body:
There is a discrepancy in pin terminology between your schematic & what TI uses in their datasheets. I don't see anything in their datasheets using I+ or I-. I only see V+ & V-. These 2 pins perform all your voltage & current measurements depending on the "mode" you tell the IC to use.

As near as I can tell based on your schematic, you should be seeing the voltage reading based on what is applied between V+ & V- (In your case, 3.3vdc) if you've told the chip to read the bus voltage channel.

You should also be getting a current reading between the V+ & V- pins if you've told the chip to read the shunt voltage channel. Since the part is designed for a full scale voltage differential of 36v between the V+ & V- pins, I suspect a reading of about 10% of max (based on a 3.3v differential).

I confess to not knowing the board or its operation but having looked it up on the TI website, it does appear to have a few jumper settings & a calibration routine to follow. There's a user guide on TI's website as well as the usual technical data pages. Perhaps those will assist in setting the jumpers correctly. [ina226 data sheet][1] & [eval board user guide][2]
[1]: http://www.ti.com/lit/ds/symlink/ina226.pdf
[2]: http://www.ti.com/lit/ug/sbou113/sbou113.pdf
bc

body:
If this is the usual Arduino-style module with a shunt resistor already in it, then with your schematic, you have [nearly] shorted your supply rail. Your schematic should have the load wired in series to the `Isense+` and `Isense-` terminals, and the `V+` and `V-` terminals should be connected in parallel across the voltage powering the load.

The current must "pass through" the `Isense` terminals, and the module has to measure the voltage across the load in order to be able to get both I and V to compute power consumption.