message:
How to send multiple data from PC to arduino

I have a project in arduino that i interface with java. The arduino is connected to the computer via usb cable , I use the serial communication.
 I have two variables:

    //Code in arduino
    int ADelay = 1000;
    int BDelay = 1000;
I want to change the value of each variable based on the input of the user using the java interface.
Is there a code that let the arduino identify that this data:

    2000
Is intended to or for:

    int ADelay
and this

    300
is for

    int BDelay

My only idea on how to achieve this is to add A or B before the number before i send to arduino

    A2000
    B300

And use Delimeter in arduino to split the data and use if else condition to decide where the data belong , Is there any other way ? Thanks

body:
The approach noted in the question – having an identifying character at the front of each number – is a workable approach.  Other approaches include:
•  always sending numbers in pairs, eg `2000,300` would denote `A2000 B300`.
•  encoding the A or B as part of the number; eg, the range 0-4999 could denote A delays of 0 to 4999, while the range 5000-9999 could denote B delays of 0 to 4999.
•  sending A delays via decimal digits, and B delays via letter-substitutes for digits; eg DAA could encode a B delay of 300.

One of the easiest-to-parse approaches is to have an identifying character at the end of each number, rather than at the front.  This allows your code to pick up digits until a letter appears, and then dispatch based on the letter.  Here's some example code:

    // Sketch that accepts numbers and action code via serial input.
    // Silently ignores any numbers not followed by a valid action letter.
    // Does not test for number overflow.      - jiw 3 Nov 2016

    void setup() {
      Serial.begin(115200);         // init serial port
    }

    unsigned int val=0;
    void loop() {
      char inc;
      while (Serial.available()) { // Get characters
        inc = Serial.read();
        if (inc >= '0' && inc <= '9') {
          val = 10*val + (inc-'0');
        } else {
          switch (toupper(inc)) {
          case 'A':
            Serial.print("Case A got ");
            Serial.println(val);
            break;
          case 'B':
            Serial.print("Case B got ");
            Serial.println(val);
            break;
          default :
           ; // handle blanks, returns, etc
          }
          val = 0; // Set val to zero after any non-digit
        }
      }
    }

---

*Edit 2:* This edit incorporates some code suggestions from comments into the answer.

---

If you need to know whether a number for val1 has been specified -- that is, if you handle items like `500B` as well as `300,500B` -- you can set/test/clear a flag:

    ...
    case ',':
      val1=val; v1flag=1;
      break;
    ...
    case 'B':
      if (!v1flag) val1=val1default;
      Serial.print("B stuff with val and val1");
      v1flag=0;
      break;
    ...

---

To retain when the power is off, you can write a `recordData()` function, that when called will write selected data to EEPROM if the value has changed.  In `setup()`, load data from where you stored it. For data validation, you can store in the cell after a value *v* its complement, *~v*.  If when you reload data it fails the validation test, use a default value instead, and write it to EEPROM for future use.

---

The code snippet shown next, from kaisarGreat's 8 May comment, has several problems to be corrected:

    case a :
      WATEREQFORN1 = val;
      EEPROM.put(0, WATEREQFORN1);
    case b :
      WATEREQFORN2 = val;
      EEPROM.put(1, WATEREQFORN2);
    case d :
      DELAY = val;
      EEPROM.put(3, DELAY);

Logic or syntax problem: Missing `break` statements at  ends of cases.  This error will allow execution to flow from one case into the next.  While there are situations where that's useful, this is not one.

Logic or syntax problem: Unless `a`, `b`, ... are declared constants they won't work as case designators.  Perhaps use `'A'`, `'B'`, ... instead.

Style problem:  Variable names in all upper case.  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`.

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 fixes some of those problems.

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


sender: user

sender: assistant

body:
If you are just looking to send something as simple as 2 integers, your approach should be fine, you just need to set your own protocol to encode the data from java and decode it on the arduino side.

Another easy way would be to set a starting byte, could be anything like 0x6A etc, (with optional checksum if it's through bluetooth or other noisy communication method):

    [8 bit starting byte][32 bit integer data A][32 bit integer data B]

On the arduino side you want to keep polling for the starting byte, once you receive the special byte then the next 32 bits would be your data A and the following 32 bits would be your data B.

However if you want something more robust or object oriented you could look into this library:
https://github.com/bblanchon/ArduinoJson

It allows you to decode and encode JSON objects which is very flexible and widely accepted, so you just need to encode the data into a JSON object on the java side and decode it using that library.


message:
How to connect an Arduino Micro to MPU-6050

So I'm trying to connect my Arduino micro to the MPU-6050. I was using this tutorial:

https://diyhacking.com/arduino-mpu-6050-imu-sensor-tutorial/

This tutorial worked with my Arduino Uno but not the Micro. When I try to run the Serial Monitor it just says "Initializing I2C Devices".

Is it the code that's not allowing to run it on the Arduino Micro or it needs a different setup than the Arduino Uno?  Thanks!

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

       // I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class using DMP (MotionApps v2.0)
    // 6/21/2012 by Jeff Rowberg <jeff@rowberg.net>
    // Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib
    //
    // Changelog:
    //      2013-05-08 - added seamless Fastwire support
    //                 - added note about gyro calibration
    //      2012-06-21 - added note about Arduino 1.0.1 + Leonardo compatibility error
    //      2012-06-20 - improved FIFO overflow handling and simplified read process
    //      2012-06-19 - completely rearranged DMP initialization code and simplification
    //      2012-06-13 - pull gyro and accel data from FIFO packet instead of reading directly
    //      2012-06-09 - fix broken FIFO read sequence and change interrupt detection to RISING
    //      2012-06-05 - add gravity-compensated initial reference frame acceleration output
    //                 - add 3D math helper file to DMP6 example sketch
    //                 - add Euler output and Yaw/Pitch/Roll output formats
    //      2012-06-04 - remove accel offset clearing for better results (thanks Sungon Lee)
    //      2012-06-01 - fixed gyro sensitivity to be 2000 deg/sec instead of 250
    //      2012-05-30 - basic DMP initialization working

    /* ============================================
      I2Cdev device library code is placed under the MIT license
      Copyright (c) 2012 Jeff Rowberg

      Permission is hereby granted, free of charge, to any person obtaining a copy
      of this software and associated documentation files (the "Software"), to deal
      in the Software without restriction, including without limitation the rights
      to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      copies of the Software, and to permit persons to whom the Software is
      furnished to do so, subject to the following conditions:

      The above copyright notice and this permission notice shall be included in
      all copies or substantial portions of the Software.

      THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
      THE SOFTWARE.
      ===============================================
    */

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

    /* =========================================================================
       NOTE: In addition to connection 3.3v, GND, SDA, and SCL, this sketch
       depends on the MPU-6050's INT pin being connected to the Arduino's
       external interrupt #0 pin. On the Arduino Uno and Mega 2560, this is
       digital I/O pin 2.
       ========================================================================= */

    /* =========================================================================
       NOTE: Arduino v1.0.1 with the Leonardo board generates a compile error
       when using Serial.write(buf, len). The Teapot output uses this method.
       The solution requires a modification to the Arduino USBAPI.h file, which
       is fortunately simple, but annoying. This will be fixed in the next IDE
       release. For more info, see these links:

       http://arduino.cc/forum/index.php/topic,109987.0.html
       http://code.google.com/p/arduino/issues/detail?id=958
       ========================================================================= */

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

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

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

    // ================================================================
    // ===                      INITIAL SETUP                       ===
    // ================================================================

    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

      // initialize serial communication
      // (115200 chosen because it is required for Teapot Demo output, but it's
      // really up to you depending on your project)
      Serial.begin(115200);
      while (!Serial); // wait for Leonardo enumeration, others continue immediately

      // NOTE: 8MHz or slower host processors, like the Teensy @ 3.3v or Arduino
      // Pro Mini running at 3.3v, cannot handle this baud rate reliably due to
      // the baud timing being too misaligned with processor ticks. You must use
      // 38400 or slower in these cases, or use some kind of external separate
      // crystal solution for the UART timer.

      // 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(1788); // 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(digitalPinToInterrupt(2), 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);
    }

    // ================================================================
    // ===                    MAIN PROGRAM LOOP                     ===
    // ================================================================

    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
        // .
        // .
        // .
        // if you are really paranoid you can frequently test in between other
        // stuff to see if mpuInterrupt is true, and if so, "break;" from the
        // while() loop to immediately process the MPU data
        // .
        // .
        // .
      }

      // 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!"));

        // otherwise, check for DMP data ready interrupt (this should happen frequently)
      } else if (mpuIntStatus & 0x02) {
        // 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);
    #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);
      }
    }

** code with `attachInterrupt(digitalPinToInterrupt(2), dmpDataReady, RISING);`**

body:
Wait and be patient. It is initializing the sensor. Have you even waited for like 10 seconds? I bet not.

 1. Run it and let it wait for 10 seconds.

 2. Add `while(!Serial);` right after `Serial.begin(115200);`.

 3. Set the baud rate to 115200. It works better in my opinion.

 4. Any other devices connected to your I2C constellation? If yes, remove all for testing purposes
 5. If it still doesn't work, reboot your PC.


body: That IMU and library require an interrupt to work correctly.  It is programmed to use interrupt 0 with this line in the setup function: `attachInterrupt(0, dmpDataReady, RISING);` This is not the proper way to do things since it cannot be transferred between arduinos.  On the Uno, interrupt 0 is pin 2 but on the Micro interrupt 0 is pin 3.  So the simple solution is to move the wire from pin 2 to pin 3.  The correct way to fix it is to change the line to this: `attachInterrupt(digitalPinToInterrupt(2), dmpDataReady, RISING);`


body: I used interrupt 4 on pin 7 and it worked great! Just had to change the interrupt pin designation to "7" in the code....


body:
I've just been through a similar issue, and here's what worked for me.

Following @mwwalk's instruction I changed the interrupt pin to digital Pin 7. After uploading the code to the Arduino Micro it would get past `Initializing I2C devices...` but end up showing `MPU6050 connection failed`. This is because `mpu.testConnection()` was unsuccessful.

To fix this I changed the connections for SCL and SDA on the MPU-6050 to digital pin 3 and digital pin 2 on the Arduino. These aren't the same as the pins shown in the diagram in the tutorial (A5 and A4).

The [pin mapping for the Arduino Micro][1] lists Digital Pin 2 as the SDA pin and Digital Pin 3 as the SCL pin. Connecting SDA to Digital Pin 2 and SCL to Digital Pin 3 worked for me.

  [1]: https://www.arduino.cc/en/Hacking/PinMapping32u4


message:
The use of 4.7kOhm resistor with DS18B20 temperature sensor

I was using a temperature sensor DS18B20 with Arduino.

I've [read][1] that you should connect the digital input line and the 5V line with a 4.7kOhm resistor - like in the picture.

Can someone explain why do we need to do this? And why this resistance? What happens if we don't put a resistor at all or use a different resistance?

[![Dallas DS18B20 with the 4.7kOhm resistor][2]][2]

  [1]: https://arduino-info.wikispaces.com/Brick-Temperature-DS18B20
  [2]: https://i.stack.imgur.com/T1O4j.jpg

body:
The product page FAQ [https://www.maximintegrated.com/en/support/faqs/ds18b20-faq.html] has an entry:

    Q: Is the 4.7kΩ resistor needed for 5V and 3.3V operation?
    A: Yes, the 4.7kΩ pullup resistor is required for both 5V and 3.3V applications.

The 1-wire bus requires that the control signal be pulled high so the master device can pull it low to ask for data, and the slave device can pull it low to give the data. This allows you to have multiple 1-wire devices on the same "one wire".

The data sheet notes another purpose:

    Another feature of the DS18B20 is the ability to operate
    without an external power supply. Power is instead
    supplied through the 1-Wire pullup resistor through the
    DQ pin when the bus is high. The high bus signal also
    charges an internal capacitor (CPP), which then supplies
    power to the device when the bus is low. This method of
    deriving power from the 1-Wire bus is referred to as “parasite
    power.” As an alternative, the DS18B20 may also be
    powered by an external supply on VDD.


body:
Adding to jose's answer above to answer your other two questions

And why this resistance?
 When the device doesnt have its own power supply it uses the power going through the pull up resistor-thus with this resistance it is powered properly. Also the other reason- as Jose wrote is because it the value which differentiates high or low bits.

What happens if we don't put a resistor at all or use a different resistance?
If you are going to you an out of spec value-dont expect the device to work properly because its using the wrong resistance-e.g. it may not work because if the resistance is too high-then according to ohms law it may not receive enough parasitic power. Though it should be able to tolerate the error tolerance of the resistor-so changing it by a few ohms either way from 4700 ohms will not make a difference. You may damage the device without a resistor.


message:
Use digital pins as analog - Arduino Micro

I have an Arduino Micro and I want to use pin 6 and 8 as an analog pin, according to the manual this is possible:

> The Micro has a total of 12 analog inputs, pins from A0 to A5 are
> labelled directly on the pins and the other ones that you can access
> in code using the **constants** from A6 trough A11 are shared respectively
> on digital pins 4, 6, 8, 9, 10, and 12.

What exactly do they mean by constants? I am aware what a constant is in the scope of programming, however I'm not sure what I should use to assign pins 6 and 8 as an analog pin? I assume I cannot just do an `analogRead(6)`?

body:
Constants are variables that cannot change. They are constant.

In this case they are variables that have been set up in the board definition files (in pins_arduino.h in case you're interested) and are named just as they have said - `A6` through `A11`.  This complements the existing `A0` through `A5` that are normally there anyway.

So you just use those names and it chooses the right pin for you:

    int val = analogRead(A8);

The definitions of the pins are:

    static const uint8_t A0 = 18;
    static const uint8_t A1 = 19;
    static const uint8_t A2 = 20;
    static const uint8_t A3 = 21;
    static const uint8_t A4 = 22;
    static const uint8_t A5 = 23;
    static const uint8_t A6 = 24;   // D4
    static const uint8_t A7 = 25;   // D6
    static const uint8_t A8 = 26;   // D8
    static const uint8_t A9 = 27;   // D9
    static const uint8_t A10 = 28;  // D10
    static const uint8_t A11 = 29;  // D12

So no you cannot just use the number `8`, you have to use `A8` which points to pin number `26`. The Arduino core then interprets that number as an analog pin (as opposed to the digital pin, which is 8) and performs an analog read on it.


message:
Speed up the Arduino

I wrote a code that controls a stepper motor using the AccelStepper library. When it receives a serial signal from Visual Basic that contains a coordinate value, the Arduino will control the stepper motor by this value. The code works very well but it runs 1 second after receiving the value over the serial port. I want the code to run faster. Here is the code:

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

    #include <AccelStepper.h>
    #include <MultiStepper.h>
    #include <AccelStepper.h>
    #include <MultiStepper.h>
    #include <AccelStepper.h>

    // Define a stepper and the pins it will use
    AccelStepper stepper(1, 9, 8);

    int pos = 0;

    void setup()
    {
      Serial.begin(115200);
      stepper.setMaxSpeed(90);
      stepper.setAcceleration(90);
    }

    void loop()
    {
      if (Serial.available()) {
        int steps = Serial.parseInt();
        stepper.moveTo(steps);

        if (stepper.distanceToGo() == 0) {
          stepper.moveTo(stepper.currentPosition());
          stepper.setSpeed(100);
        }
      }
      stepper.run();
    }

body:
Do not use parseInt(): it will wait for one second to make sure there are no digits pending.

 -Edgar Bonet


body:
As others have said, this issue is created because the parseInt function reads in characters until it receives a non numeric character or until it reaches the timeout value, which is set at 1000 ms (1 second). There are a couple of ways to fix this, order most difficult to least:

1. Instead of just sending a number, send a number and then a letter at the end. So instead of sending "123", you would send "123x".  `parseInt()` will immediately return when it hits the x.  However, you'll still have the x in the stream so you'll need to manually read it and discard it.
2. Make the value that is sent a set number of digits - say 4 for example.  Since you know it will be four digits, use a for loop to read in four characters and build it into a number by multiplying.  If you read in digit1, digit2, digit3, digit4 then the number is `1000 * digit1 + 100 * digit2 + 10 * digit3 + digit4`.
3. Make the timeout value for `parseInt()` smaller.  `parseInt()` inherits from the Stream class so you would use `Serial.setTimeout(50)` in the setup function to change it to a 50 ms timeout.


message:
Setup arduino uno with ESP8266 ESP-1

Iam trying to set up the `arduino uno` with the wifi module `ESP8266`. I use this schematic setup:

[![IMAGE][1]][1]

I have followed this tutorial: [Tutorial ESP8266][2]

Thereby I removed the `Mega328P Chip` like it says above, I can communicate trough my terminal in the `arduino IDE` with the `ESP-module` but when I want to upload an simple test file like this:

    #include <SoftwareSerial.h>

    SoftwareSerial ESP8266(0, 1); // RX = 8 en TX = 9

    boolean FAIL_8266 = false;

    void setup() {
      // put your setup code here, to run once:
       do {
        ESP8266.begin(115200); // start communicatie met esp8266

        //Wait Serial Monitor to start
        while (!Serial);

        ESP8266.print("AT\r\n");

        delay(500);

        if (ESP8266.find("OK")){
            ESP8266.print("ready");
        }

       } while (FAIL_8266);
    }

    void loop() {
      // put your main code here, to run repeatedly:

    }

Than it keeps throwing me this error: `avrdude: stk500_getsync() attempt x of x: not in sync: resp=0x20` is it because I removed the `Mega328P Chip`?

Thereby I've tried the test code from the tutorial here is an link to the code: [LINK][3].

There it keeps saying that `Serial2 was not declared in scope`

I'll hope someone can help me out on this one and run an simple test script to communicate with the `ESP8266 WIFI Module`

  [1]: https://i.stack.imgur.com/2mtJC.jpg
  [2]: http://www.instructables.com/id/noobs-guide-to-ESP8266-with-Arduino-Mega-2560-or-U/step2/Software-needed/
  [3]: https://gist.github.com/teos0009/2f61b6b031a6eb35c48b

body:
You must have your microcontroller in place if you are uploading code to it.

You can talk to ESP8266 via serial monitor because you are connected directly to the pins of your USB-UART bridge.

Place your uC back, change this line of code:

SoftwareSerial ESP8266(0, 1);

to this one:

SoftwareSerial ESP8266(8, 9);

and change your wires accordingly(what was on pin 0, now connect to pin 8, pin 1 to pin 9).
Now your Atmega can talk to ESP8266 after you upload the code.

btw. "Serial2" is Serial port for more advance Arduino boards, it won't work on Atmega328 based board.


body:
The first, most obvious issue (besides needing the MCU on the Arduino board!) is that you need to cross-connect the RX and TX lines between the two boards. You have both RXes connected together, and both TXes connected together. The ESP's RX has to listen to the Arduino's TX, and vice-versa.

An easy way to remember which ESP pins are RX and TX is that the pin nearest the free ends of the antenna is the RX pin; the TX pin is diagonally opposite it.

A second, potential problem, is that the ESP board may draw more power than the Arduino's 3.3v regulator can provide. If it is making brief and not too frequent transmissions, you may get away with it, but the ESP can easily out-draw the regulator and it's 3.3v supply will sag.


message:
Why does exit status 1 stray '\302' in program pop up around Serial.println ( "-> Second Service load");?

/*
     Controlling a servo position using a potentiometer (variable resistor)
     by Michal Rinott <http://people.interaction-ivrea.it/m.rinott>

     modified on 8 Nov 2013
     by Scott Fitzgerald
     http://www.arduino.cc/en/Tutorial/Knob
    */

    #include <Wire.h>
    #include "ds3231.h"
    #include <Servo.h>
    int potpin = 0; // Analog pin is used to connect the potentiometer
    int val; // Variable to read the value from the analog pin
    int pause = 800; // Delay in open feeders (feed amount)

    Servo myservo;  // create servo object to control a servo

    #define BUFF_MAX 256

    // First Service
    uint8_t wake_HOUR1 = 12;
    uint8_t wake_MINUTE1 = 56;
    uint8_t wake_SECOND1 = 0;

    // Second Service
    uint8_t wake_HOUR2 = 18;
    uint8_t wake_MINUTE2 = 30;

    // How often to update the information to the standard output (ms)
    unsigned long prev = 5000, interval = 5000;

    void setup() {
      myservo.attach(9);  // attaches the servo on pin 9 to the servo object
      myservo.write (0); // Set the position to 0

      Serial.begin (9600);
      Wire.begin ();
      DS3231_init (DS3231_INTCN);
      DS3231_clear_a1f ();
      DS3231_clear_a2f ();
      set_alarm ();
    }

    void loop()
    {
       char buff [BUFF_MAX];
      unsigned long now = millis ();
      struct ts t;

      // Output through time (5000ms) The time and alarm clocks ustanovlennnye
      if ((now - prev> interval) && (Serial.available () <= 0)) {
        DS3231_get (& t);

        // Display current time
        snprintf (buff, BUFF_MAX, ".% d% 02d% 02d% 02d:.% 02d:% 02d", t.year,
                 t.mon, t.mday, t.hour, t.min, t.sec);
        Serial.println (buff);

        // Display a1 debug info
        DS3231_get_a1 (& buff [0], 59);
        Serial.println (buff);
        DS3231_get_a2 (& buff [0], 59);
        Serial.println (buff);

        if (DS3231_triggered_a1 ()) {
          // INT has been pulled low
          Serial.println ( "-> First Service load");

      myservo.write(10);                  // sets the servo position according to the scaled value
      delay(1000);                           // waits for the servo to get there
      myservo.write(170);                  // sets the servo position according to the scaled value
      delay(1000);                           // waits for the servo to get there

          // Clear a1 alarm flag and let INT go into hi-z
          DS3231_clear_a1f ();
        }
        if (DS3231_triggered_a2 ()) {
          // INT has been pulled low
          Serial.println ( "-> Second Service load");

      myservo.write(10);                  // sets the servo position according to the scaled value
      delay(1000);                           // waits for the servo to get there
      myservo.write(170);                  // sets the servo position according to the scaled value
      delay(1000);
    }

body:
 As Gerben notes, the stackoverflow question *[error: stray '\302' in program](https://stackoverflow.com/q/5167656)* is about this issue.  Basically, your file contains one or more characters not valid in the current character set.  The character is either non-printing or a multi-byte unicode character.

How did the character get there? Some of the ways mentioned in the stackoverflow question are pressing ctrl-space or shift-space.

How to find the character and get rid of it?  You can look at output from hex-dumping the file, which will identify all characters definitively.  Or by trial and error you can delete and retype spaces in the region of the error.


message:
Odd symbols in ESP8266 responses to AT commands

I used the code below to control an ESP8266.  I am getting some unknown symbols in the responses.

    #include <SoftwareSerial.h>
    const byte rxPin=2;
    const byte txPin=3;
    SoftwareSerial ESP8266( rxPin, txPin);

    void setup() {
      Serial.begin(115200);
      ESP8266.begin(115200);
      delay(1000);
      // put your setup code here, to run once:

    }

    void loop() {
      Serial.println("sending an AT command");
      ESP8266.println("AT");

      delay(100);
      while(ESP8266.available())
      {
        String inData = ESP8266.readStringUntil('\n');
        Serial.println("Got Response:" + inData);
        delay(1000);
          ESP8266.println("AT+RST");
        }
      // put your main code here, to run repeatedly:

    }

The unknown symbols are shown in the screen shot.

[![unknown symbols](https://i.stack.imgur.com/LRDF4.jpg)](https://i.stack.imgur.com/LRDF4.jpg)

What might the problem be?

body: I nutted over this for quite a while. If you look up the reference for SoftwareSerial - https://www.arduino.cc/en/Reference/SoftwareSerial - and look at the limitations, you'll find that it won't work above 57k baud rate and pins 2 and 3 wont support change interrupts, whatever they are.  Sometimes I think some of these projects are untested.  I think I'll use the hardware ports on two arduinos and use SoftwareSerial on the right pins and baud rate to get the two arduinos to communicate, or use Software serial to talk to the pc through a MAX232.  I don't think you'll get a 115200 baud esp to talk SoftwareSerial


message:
How to run multiple functions one after another?

I want to fade a red LED up and down, then a green LED up and down, and repeat the whole cycle indefinitely.

I've been trying to run multiple functions one after another. However my current code seems to have them both fading in parallel.

I tried using a `switch case`, `do while` and the `while` loop but the code runs the two functions at once. So what is wrong with the code below?

This is my code:

    void setup() {
        Serial.begin(9600);
        DDRD |= (1<<DDD6)|(1<<DDD5);
        TCCR0A = 0xF1;
    }

    uint8_t fade_seq;

    void loop() {
        loop1:
        fade_seq++;
        while (fade_seq==1)
        {
            fade_red(1);
        }
        Serial.println(fade_seq);
        while (fade_seq==2)
        {
            fade_green(1);
        }
        if (fade_seq==3)
        {
            fade_seq=0;
            goto loop1;
        }
    }

    void fade_red(uint8_t cnt)
    {
        uint8_t i,k;
        for (k=0;k<cnt;k++)
        {
            OCR0A+=1;
            _delay_ms(10);
            if (OCR0A == 255)
            {
                for (i=0;i<255;i++)
                {
                    OCR0A--;
                    _delay_ms(10);
                }
            }
        }
    }

    void fade_green(uint8_t cnt)
    {
        uint8_t i,k,c;
        for (c=0;c<cnt;c++)
        {
            for (k=0;k<255;k++)
            {
                OCR0B+=1;
                _delay_ms(10);
                if (OCR0B == 255)
                {
                    for (i=0;i<255;i++)
                    {
                        OCR0B--;
                        _delay_ms(10);
                    }
                }
            }
        }
    }

body:
try this-and add to it calling a function in between-as discussed in comments that gives a visible delay-note I increased the delays as its probably going too fast

    uint8_t fade_seq=1;
     void setup() {
    DDRD |= (1<<DDD6)|(1<<DDD5);
    TCCR0A = 0xF1;
    }

    void loop() {
    fade_seq++;
    if (fade_seq==1)
    {
      fade_red(1);

    }

    if (fade_seq==2)
    {
      fade_green(1);

    }
    if (fade_seq==3)
    {
    fade_seq=0;
    }
    }

    void fade_red(uint8_t cnt)
    {
      uint8_t i,k;
      for (k=0;k<cnt;k++)
      {
        OCR0A+=1;
        _delay_ms(100);
        if (OCR0A == 255)
        {
          for (i=0;i<255;i++)
          {
            OCR0A--;
            _delay_ms(100);
          }
        }
      }
    }

    void fade_green(uint8_t cnt)
    {
      uint8_t i,k;
      for (k=0;k<cnt;k++)
      {
        OCR0B+=1;
        _delay_ms(1-0);
        if (OCR0B == 255)
        {
          for (i=0;i<255;i++)
          {
            OCR0B--;
            _delay_ms(100);
          }
        }
      }
    }


body:
It simply is not possible for the processor to run both functions at once. What probably is happening is that the sequence of functions executes too fast to distinguish it as two sequential processes. You'll need to do something like call them with a delay in between. It could be as simple as:

    void loop() {
       fade_red();
       delay(500);

       fade_green();
       delay(500);
    }

The while loops surrounding your calls do nothing at all. The effect of each one is to call its respective function once. Your code is pretty much equivalent to a switch/case statement using fade_seq as the selector, but without any control over the timing of your calls, the functions will happen in rapid sequence.


body:
I did not quite understand what you are _actually_ trying to accomplish.
Neither you question nor your code is very clear in this respect. And
your code is probably buggy anyway, since it does not do what you
expect.

Then, I am just guessing: you may just want to fade a red LED up and
down, then a green LED up and down, and repeat the whole cycle
indefinitely. I am guessing right?

First of all, I would recommend you stick with the functions provided by
the Arduino core library, as they will make your life easier. The kind
of low level AVR programming you are attempting here is for advanced
users. You should learn the basics first before moving to that realm.

Here is how I would write that using the plain `analogRead()` function:

    const uint8_t RED   = 6;  // pin connected to the red LED
    const uint8_t GREEN = 5;  // pin connected to the green LED

    void setup()
    {
        Serial.begin(9600);
        pinMode(RED, OUTPUT);
        pinMode(GREEN, OUTPUT);
    }

    // Fade an analog pin up and down.
    void fade(uint8_t pin)
    {
        for (int i = 1; i <= 255; i++) {
            analogWrite(pin, i);
            delay(10);
        }
        for (int i = 254; i >= 0; i--) {
            analogWrite(pin, i);
            delay(10);
        }
    }

    void loop()
    {
        Serial.println(F("Fading RED."));
        fade(RED);
        Serial.println(F("Fading GREEN."));
        fade(GREEN);
    }

Each LED fading up and down takes roughly 5 seconds:
2 ramps × 255 steps/ramp × 10 ms/step.


body:
> Why my loops are very complicated?

OK, here is your loop:

    uint8_t fade_seq;   // <--- initially zero

    void loop() {
    loop1:
    fade_seq++;
    while (fade_seq==1)
    {
      fade_red(1);
    }
    Serial.println(fade_seq);
    while (fade_seq==2)
    {
      fade_green(1);
    }
    if (fade_seq==3)
    {
      fade_seq=0;
      goto loop1;
    }
    }

So you add 1 to `fade_seq` and then:

    while (fade_seq==1)
    {
      fade_red(1);
    }

So `fade_seq` is always 1 so that loops indefinitely. Therefore you can forget about everything else after it.

So you may as well write:

    void loop() {
       while (true)
        {
        fade_red(1);
        }
     }

And since `loop`, well, loops, that simplifies to:

    void loop() {
        fade_red(1);
       }


body:
OK I did it :)

    void setup() {
    DDRD |= (1<<DDD6)|(1<<DDD5);
    TCCR0A = 0xF1;
    }

    void loop() {
      fade_red(255);
      fade_green(255);
    }

    void fade_red(uint8_t cnt)
    {
      uint8_t i,k;
      for (k=0;k<cnt;k++)
      {
        OCR0A++;
        _delay_ms(10);
        if (OCR0A == 255)
        {
          for (i=0;i<255;i++)
          {
            OCR0A--;
            _delay_ms(10);
          }
        }
      }
    }
    void fade_green(uint8_t cnt)
    {
      uint8_t i,k;
      for (k=0;k<cnt;k++)
      {
        OCR0B++;
        _delay_ms(10);
        if (OCR0B == 255)
        {
          for (i=0;i<255;i++)
          {
            OCR0B--;
            _delay_ms(10);
          }
        }
      }
    }


message:
Use TFT LCD with Uno and Wi-Fi shield

I need to work with Arduino Uno, LCD and Wi-Fi shield.

I was wondering whether I can use the LCD in the link, [2.2" TFT Display - Test the Display][1] with the Uno and Wi-Fi shield - and how to search for them?

  [1]: https://learn.adafruit.com/2-2-tft-display/test-the-display

body: Yes the arduino Uno will work with that LCD display and can work with wifi shield at same time too.


body:
Start by checking which pins are used by the shields and if there is any conflicts. Check the shield schematics and example libraries.

If there are any conflicts, check if the shields has any jumpers that may be used to change the pin configuration.

Cheers!


body: Providing they're I2C shields, it is possible to use both at the same time, you may have to write your own modifications to allow this however as each shields library may assume it is the sole connected shield.


message:
How to use different device address for MCP23017 so I can use multiple chips?

I want to use more than 3 MCP23017-E/SP DIP28 chips so I can use many digital pins. I use [Adafruit-MCP23017-Arduino-Library][1]. I tried [this][2] solution but only device address with 0x00 is working.

**The question is** what device address should I use for additional chip?
[![enter image description here][3]][3]

  [1]: https://github.com/adafruit/Adafruit-MCP23017-Arduino-Library
  [2]: https://stackoverflow.com/questions/36954218/how-to-use-multiple-mcp23017-chips-with-the-adafruit-mcp23017-h-library
  [3]: https://i.stack.imgur.com/aJDTz.jpg

    #include "Adafruit_MCP23017.h"
    Adafruit_MCP23017 mcp1;
    #define addr1 0 // tested 1,2,3,4,5, 0x01, 0x02, 0x20, 0x21 but only 0 and 0x00 is working.
    void setup()
      {
        mcp1.begin(addr1);
        mcp1.pinMode(0, INPUT); //pin 21 on chip
        Serial.begin(9600);
      }

      void loop()
      {
          if(mcp1.digitalRead(0)== HIGH )
          Serial.println("HIGH");
      }

body:
I share my solution with 7 [MCP23017][1] chip , 7x14 pins=98 pins using [adafruit library][2].

**Connections:**

    addr 0 = A2 low , A1 low , A0 low  000
    addr 1 = A2 low , A1 low , A0 high 001
    addr 2 = A2 low , A1 high , A0 low  010
    addr 3 = A2 low , A1 high , A0 high  011
    addr 4 = A2 high , A1 low , A0 low  100
    addr 5 = A2 high , A1 low , A0 high  101
    addr 6 = A2 high , A1 high , A0 low  110
    addr 7 = A2 high, A1 high, A0 high 111

    Connect pin #12 of the expander to Analog 5 (i2c clock)
    Connect pin #13 of the expander to Analog 4 (i2c data)
    Connect pins #15, 16 and 17 of the expander to ground (address selection)
    Connect pin #9 of the expander to 5V (power) // operation voltage is 1.8 to 5.5
    Connect pin #10 of the expander to ground (common ground)
    Connect pin #18 through a ~10kohm resistor to 5V (reset pin, active low)

    Input #0 is on pin 21 so connect a button or switch from there to ground

  [1]: http://microelk.azurewebsites.net/Images/MCP23017/MCP23017_PINOUT.jpg
  [2]: https://github.com/adafruit/Adafruit-MCP23017-Arduino-Library

**Code:**

    #include <Adafruit_MCP23017.h>

    Adafruit_MCP23017 mcp1; // chip 1
    Adafruit_MCP23017 mcp2; // chip 2

    #define addr1 7 // 7 = A2 high, A1 high, A0 high
    #define addr2 0 // 0 = A2 high, A1 high, A0 high
    void setup()
      {
        Serial.begin(9600);
        mcp1.begin(addr1);
        mcp2.begin(addr2);

        mcp1.pinMode(0, INPUT); //pin 21 on chip
        mcp2.pinMode(0, INPUT); //pin 21 on chip

      }

      void loop()
      {
          if(mcp1.digitalRead(0)== HIGH )
          Serial.println("HIGH");
          delay(1000);

          if(mcp2.digitalRead(0)== HIGH )
          Serial.println("HIGH 2");
          delay(1000);
      }


message:
How to connect a varying output voltage to the Arduino?

I have a smart meter and I want to connect my output pulse meter to the Arduino in order to count the pulses, but the problem is my  output pulse voltage is varying (between 1V to 17V approximately) and the Arduino accepts only a stable voltage (5V).

Therefore, how can I make my output pulse voltage stable to connect it to the Arduino?![enter image description here](https://i.stack.imgur.com/JQ65g.png)

body:
If “what I want is counting the pulses of my meter” means that you want to count the number of pulses the meter produces, you can use a circuit like the following to clip the voltage into the 0-to-5V range (as acceptable for inputs on Uno digital pins).

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

<!-- End schematic -->

Then, to count pulses, write a sketch that repeatedly reads the selected input pin.  Each time it changes from low to high, add one to your count of pulses.

If you don't have 5.1V zener diode like the 1N4733A, you could instead attach the anode of an ordinary diode to the junction of R1,R2 and its cathode (the cross-bar end) to 3.3V on the Uno.  This will clamp the voltage on the input pin to at most about 4V.  (Note, with such a diode clamp, there would be high-current problems if you subsequently changed the pin to a high output.  You could of course put a 100Ω resistor in series with the clamp diode if you are concerned about that.)


message:
Alter baud rate after being certain events

I'm using my HC-05 (Master) to receive strings from a sensor (Slave). Each string is supposed to have 7 items divided by ',' like so:

>a,b,c,d,e,f,g

But it isn't always received in such a manner. Sometimes it's 1.5 of a string or 2 strings in 1. I have tested the sensor with its native software and others, so the sensor shouldn't be the problem. So I believe it may be a baud rate issue. I tried to increase the HC-05's baud rate to 115200, but wasn't able to test anything because I need to use AT commands at the beginning of the program and for that the baud rate has to be 38400.

Is there any way to change the baud rate for Serial after the fact?

PS: I'm using a Mega 2560 and the sensor has a sample rate of 8Hz.

    #include <SoftwareSerial.h>
    #include <SD.h>

    String test="";
    char aux;
    File myFile;

    void setup() {
      pinMode(22, OUTPUT);
      digitalWrite(22,HIGH);
      Serial1.begin(38400);
      Serial.begin(38400);
      Serial.println("To begin capture press any key and enter");
      while(!Serial.available());
      Serial1.println("AT+INIT");
      while(!Serial1.available());
      Capture();
    }

    void Capture() {
      while(!Serial1.available());
      for(int i=0;i<2;i++) {
        delay(125);
        while(Serial1.available()) {
          aux=Serial1.read();
          Serial.print(aux);
        }
      }
      Serial.println("END");
    }

    void loop() {
    }

body: To answer your specific question, yes you can alter the baud rate after an event.  Just use a `Serial.end()` then a `Serial.begin()` with the new baud rate.


message:
Switch case problem in Arduino code

I am trying to develop an IR remote for appliances. I have written Arduino code for this purpose. I have used switch case to determine an action from the corresponding IR decode result (HEX), but I am not getting the output.

My code is:

    #include <IRremote.h>

    int RECV_PIN = 6;
    int led = 13;//1FE50AF
    int led1 = 12;//1FED827

    boolean previousState=LOW;
    boolean previousState1=LOW;
    boolean state;
    boolean state1;
    IRrecv irrecv(RECV_PIN);

    decode_results results;

    void setup() {
      Serial.begin(9600);
      pinMode(13,OUTPUT);
      pinMode(12,OUTPUT);
      irrecv.enableIRIn();// Start the receiver
    }

    void loop() {
      if (irrecv.decode(&results)) {
        Serial.println(results.value, HEX);
        switch(results.value) {
           case '0x1FE50AF':
           if (previousState == LOW) {
             state=HIGH;
             digitalWrite(led,state);
             Serial.println("LED ON");
             previousState=state;
           } else {
             state=LOW;
             digitalWrite(led,state);
             Serial.println("LED Off");
             previousState=state;
           }
           break;

           case '0x1FED827':
           if (previousState1 == LOW) {
             state=HIGH;
             digitalWrite(led1,state1);
             Serial.println("LED ON");
             previousState1=state1;
           } else {
             state1=LOW;
             digitalWrite(led1,state1);
             Serial.println("LED off");
             previousState1=state1;
           }
           break;
        }
        irrecv.resume(); // Receive the next value
      }
    }

body:
Replace all:

    case '0xZZZZZZZZ':

with:

    case 0xZZZZZZZZ:

That's because `value` in `decode_results` structure is declared as `unsigned long`, `0xZZZZZZZZ` is an `unsigned long`, but `'0xZZZZZZZZ'` is not (actually, it should not even compile).


message:
Problem with executing a function in the middle of a 'nested for loop'

New to Arduino here. I was wondering if there was anything wrong about my utilization of the nested 'for loop'. What i wanted is the execution of the 'looper4' and 'looper6' function if any of my Togglestates condition are met during the looping process. My Togglestates reads the state of my Togglepins which are linked to my toggle switches. Funny enough, the program executes the 'looper6' function immediately when i flip the switch. However, does not execute the 'looper4' function until the whole nested 'for loops' are finished even when the switch is flipped. All my outputs are to LEDs.

    int ledPins[] = { 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 26, 28};
    int pinCount = 12;
    int patternCount = 24;
    int ledLevel = 0;
    int Togglepin = 7;
    int Togglestate = 0;
    int Togglepin2 = 2;
    int Togglestate2 = 0;
    int Togglepin3 = 4;
    int Togglestate3 = 0;

    void setup()
     {

      for(int thisPin = 0; thisPin < pinCount; thisPin++)
        {
          pinMode(ledPins[thisPin], OUTPUT);
        }
      for(int thisPin = 0; thisPin < pinCount; thisPin++)
        {
          pinMode(ledPins[thisPin], OUTPUT);
        }
          pinMode(Togglepin, INPUT);
          pinMode(Togglepin2, INPUT);
          pinMode(Togglepin3, INPUT);
      }

     void loop()
     {
     looper3();
     }

     void looper() //All my loopers(1,2,6,7) execute a similar coding with
                     difference in arrays and toggling conditions(found below)
     {

      byte AOM0[]={0,0,0,0,0,0,0,0,0,0,0,0};
      byte AOM1[]={1,1,1,1,1,1,1,1,1,1,1,1};
      byte AOM2[]={1,1,1,1,1,1,1,1,1,1,1,1};
      byte AOM3[]={1,1,1,1,1,1,1,1,1,1,1,1};
      byte AOM4[]={1,1,1,1,1,1,1,1,1,1,1,1};
      byte AOM5[]={1,1,1,1,1,1,1,1,1,1,1,1};
      byte AOM6[]={1,1,1,1,1,1,1,1,1,1,1,1};
      byte AOM7[]={1,1,1,1,1,1,1,1,1,1,1,1};
      byte AOM8[]={1,1,1,1,1,1,1,1,1,1,1,1};
      byte AOM9[]={1,1,1,1,1,1,1,1,1,1,1,1};
      byte BOM0[]={1,1,1,1,1,1,1,1,1,1,1,1};
      byte BOM1[]={1,1,1,1,1,1,1,1,1,1,1,1};
      byte BOM2[]={1,1,1,1,1,1,1,1,1,1,1,1};
      byte BOM3[]={1,1,1,1,1,1,1,1,1,1,1,1};
      byte BOM4[]={1,1,1,1,1,1,1,1,1,1,1,1};
      byte BOM5[]={1,1,1,1,1,1,0,0,0,0,0,0};
      byte BOM6[]={1,1,1,1,1,1,1,1,1,1,1,1};
      byte BOM7[]={1,1,1,1,1,1,0,0,0,0,0,0};
      byte BOM8[]={1,1,1,1,1,1,1,1,1,1,1,1};
      byte BOM9[]={1,1,1,1,1,1,0,0,0,0,0,0};
      byte COM0[]={1,1,1,1,1,1,1,1,1,1,1,1};
      byte COM1[]={1,1,1,1,1,1,0,0,0,0,0,0};
      byte COM2[]={1,0,1,0,1,0,1,0,1,0,1,0};
      byte COM3[]={1,1,1,1,1,1,1,1,1,1,1,1};

      byte* All[24] = { AOM0, AOM1, AOM2, AOM3, AOM4, AOM5, AOM6, AOM7,
                        AOM8, AOM9, BOM0, BOM1, BOM2, BOM3, BOM4, BOM5,
                        BOM6, BOM7, BOM8, BOM9, COM0, COM1, COM2, COM3 };

        for (int Pattern = 0; Pattern < patternCount; Pattern++)
          {
          delay(500);
            for (int thisPin = 0; thisPin < pinCount; thisPin++)
              {
                 Togglestate3 = digitalRead(Togglepin3);
                 Togglestate = digitalRead(Togglepin);
                 digitalWrite(ledPins[thisPin],All[Pattern][thisPin]);
                 if (Togglestate3 == HIGH && Togglestate == HIGH)
                     {
                    for (int thosePin = 0; thosePin < pinCount; thosePin++)
                        {
                        digitalWrite(ledPins[thosePin],LOW);
                        }

                     looper4();

                     }
                 else if (Togglestate3 == HIGH && Togglestate == LOW)
                     {
                    for (int thatPin = 0; thatPin < pinCount; thatPin++)
                        {
                        digitalWrite(ledPins[thatPin],LOW);
                        }
                     looper6();

                     }

                 }
            }
      }

These are the functions that i used to read and toggle between the different 'looper' functions.

     void looper3()

     {
      Togglestate = digitalRead(Togglepin);

           if(Togglestate == HIGH)
             {
             looper4();
             }
            else if(Togglestate == LOW)
             {
             looper5();
             }

     }

     void looper4()

     {
      Togglestate2 = digitalRead(Togglepin2);
      Togglestate = digitalRead(Togglepin);

             if(Togglestate2 == HIGH && Togglestate == HIGH)
              {
              looper1();
              }
             else if(Togglestate2 == LOW && Togglestate == HIGH)
              {
              looper2();
              }

      }

     void looper5()

     {
      Togglestate3 = digitalRead(Togglepin2);
      Togglestate = digitalRead(Togglepin);

             if(Togglestate3 == HIGH && Togglestate == LOW)
              {
              looper6();
              }
             else if(Togglestate3 == LOW && Togglestate == LOW)
              {
              looper7();
              }

      }

Here is the toggling conditions for all my looper functions

     // Togglestate is the toggle switch i use to interchange between my 2 other
        toggle switches

     Looper1() - if (Togglestate2 == LOW && Togglestate == LOW) -> looper5();
               - if (Togglestate2 == LOW && Togglestate == HIGH) -> looper2();

     Looper2() - if (Togglestate2 == HIGH && Togglestate == LOW) -> looper5();
               - if (Togglestate2 == HIGH && Togglestate == HIGH) -> looper1();

     Looper6() - if (Togglestate3 == LOW && Togglestate == HIGH) -> looper4();
               - if (Togglestate3 == LOW && Togglestate == LOW) -> looper7();

     Looper7() - if (Togglestate3 == HIGH && Togglestate == HIGH) -> looper4();
               - if (Togglestate3 == HIGH && Togglestate == LOW) -> looper6();

This would be pretty much the whole program. I appreciate and welcome any response. Thanks!

body:
You can nest for loops fine. What you cannot do is neat for loops in loops where you name the variables the same thing.

    For thisPin ...
       For thisPin ...
       For thisPin...

It gets the compiler confused - or at the very least it gets me confused.  You can use the same have if the loops are next to each other, but not if they are nested:

    For thisPin...
        For otherPin...
        For otherPin...

Also, without seeing your whole code I cannot be sure, but you may be suffering from unexpected recursion. This is where function a calls function b which calls function a again. With no limiting factor on the call depth you end up with a stack a mile high, or on chips with a limited hardware stack you loose lots and lots of old stack data and can never get back again.


message:
Mini Voice Recorder for Arduino

I am trying to find a small voice recorder that I can use with my Arduino Micro, and I found [this](https://www.sparkfun.com/products/retired/10653). It is exactly what I am looking for, but it is now a retired product. I googled `ISD1932`, but many other sites are out of stock or not selling it anymore. Is there something of this size that does the same things, and why is it retired?

body:
It's retired because there is no market for it any more. Modern microcontrollers are more than powerful enough to handle simple audio without the need for external chips like that.

Some can even do full blown multi-channel HD audio with just the addition of a CODEC chip (that's a fancy name for a DAC to you and me).

Even a lowly 8-bit Arduino can play audio directly (though at low quality) through PWM from an SD card.


body: ISD 1820 voice recorder module for arduino. Or ISD series or ISD 1700 series voice recorder module. Which I think you can still buy these. Will work  with 8bit CPU. Or can be interfaced to 8 bit CPU. You could use multiple modules to increase recording times. I can give you more of an answer if you tell me more about your problem. ISD4004 IC can record for 8 minutes.


body: FYI, these ISD chips sample audio and store a variable charge on a single flash like cell. They do not convert a sample to a numerical value. There is no data to be read from the chips nor (AFAIK) is there an opportunity to write data to play back to the chips. AFAIK, for us common people, each ISD chip needs to have its recording entered individually. Think of it like duplicating cassette tapes. Think about this when considering how to go about building your project.


message:
Using SPI without driving MISO

I am developing an application where an Arduino Pro Mini communicates with a 12-bit ADC over SPI. The communication is one-way, meaning that the ADC will only send data back to the Arduino, not receive any. The MOSI pin is therefore not required in my application, only SCK and MISO.

I wish to know if there is a way to have the Arduino SPI library ignore the MOSI pin, and controlling the clock pin directly. The ADC requires 16 clock cycles to perform one conversion, sending the data back on the last 12 clock cycles. The way I have implemented it is by using SPI.transfer16() to get 16 clock cycles, and storing the return value in a 16bit variable. The downside to this is that the MOSI pin is driven, and I can therefore not use it for other purposes. I would very much like to be able to generate 16 clock cycles without the need for driving MOSI. Any ideas?

body:
You are using ADC which I suppose you have no way of changing firmware or anything to modify the protocol.
According to SPI protocol, when *Slave* receives a byte, it sends byte kind of a two shift registers in circular buffer. So even if your ADC finish the conversion it wont start communication protectively the protocol doesn't allow it.
In case if you have other ADC IC which is programmable you can implement your protocol but it wont be SPI it will be your own protocol, so be assure of it.


body:
In microcontrollers, the GPIO pins have a multiplexer to select what the pin is used for.  When you use the Arduino SPI library, the initialization function will set the multiplexer to MOSI for that pin.  You should be able to run your own initialization for that pin and overwrite whatever the SPI initialization function did.  Just make sure to call your initialization after SPI.begin().  This is the simplest solution.

If that doesn't work for some reason then you can dig into the source code for the Arduino SPI library.  This isn't too hard either.

Bitbanging is the hardest solution and shouldn't be necessary for your application.


message:
How to track revolution of DC motor?

I am currently trying to build a line follower robot that is designed to solve maze. This maze has a loop, thus it needs to know distance it already travelling (or at least I assume so, please let me know otherwise).

I am aware of a rotary encoder motor from Polulu ([for example][1]) but it's not available in my country and shipping price is too expensive.

So I need to find way around it. Should I use Stepper motor? Is there any other way? Thanks in advance.

  [1]: https://www.pololu.com/product/2821

body:
You can Use wheel encoders. You can even make your own wheel encoders with general parts like photoTransistor and lasor or led light. you can make your encoder or print it out in paper. The use little math to calculate the distance. It will give you measurement with good level of precision.

Basic principle:
[![enter image description here][1]][1]

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

more information at

[wheel Encoder][3]

[another encoder][4]

  [1]: https://i.stack.imgur.com/M0b9p.jpg
  [2]: https://i.stack.imgur.com/tEJc2.jpg
  [3]: http://www.societyofrobots.com/sensors_encoder.shtml
  [4]: http://letsmakerobots.com/node/12293


body:
You could add a rotary encoder to a motor yourself. Thought this is not as convenient as buying an all in one solution.

You can even build your own by making a disk with holes at regular intervals, and using an IR led, phototransistor pair on either side of the disk. You can even get all in one photo-interruptors. You could get them from an old computer-mouse. You might even be able to use the wheel/disk in it.

Another option is to add a magnet to the wheel, and a hall-effect sensor to the body. That way you can count the number of revolutions. (Though you probably want higher resolution than once per revolution).


body:
An optical encoder would be the best solution in my opinion. The next best thing would be to use a stepper motor. You can find plenty of stepper motors in old printers - which is good if the budget is tight.

The problem with a stepper motor is that you have no feedback on where the motor actually is. You drive it forward say 100 pulses, but without any feedback you have no idea if there was any slip or overrun. This is called [open loop][1] control.

However, both of these methods are measuring/driving the rotation of the motor. What happens if the wheel doesn't have enough grip and slips and does a sort of burnout. For this reason, I have seen some maze robots use an old mouse to measure the distance the robot has actually travelled. This was not necessarily very accurate over long distances but was a cheap way of measuring distance travelled.

  [1]: https://www.servocity.com/open-loop-vs-closed-loop


message:
Ethernet shield not working

I have an ethernet shield on an Arduino Mega 2560. I am running the code below. This is a slightly modified version of the DHCP ip printer example, namely I am setting a static IP instead of DHCP.

I was expecting to get:

    Start Ethernet
    My IP address: 192.168.178.163.

on the serial monitor. Instead I got:

    Start Ethernet
    My IP address: 0.237.237.237.

Any idea what the reason might be? If I am using DHCP (the unmodified example, commented lines in the code below), the code seems to freeze on the Ethernet.begin() call.The "Failed to configure ..." is not even printed.

Here is the sketch:

    #include <SPI.h>
    #include <Ethernet.h>

    // Enter a MAC address for your controller below.
    // Newer Ethernet shields have a MAC address printed on a sticker on the shield
    byte mac[] = {
      0x90, 0xA2, 0xDA, 0x10, 0xC1, 0x2C
    };
    byte ip[] = {192, 168, 178, 163};

    // Initialize the Ethernet client library
    // with the IP address and port of the server
    // that you want to connect to (port 80 is default for HTTP):
    EthernetClient client;

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      // this check is only needed on the Leonardo:
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      Serial.println("Start Ethernet");
      // start the Ethernet connection:
      Ethernet.begin(mac, ip);
      /*if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
        // no point in carrying on, so do nothing forevermore:
        for (;;)
          ;
      }*/
      // print your local IP address:
      printIPAddress();
    }

    void loop() {

      switch (Ethernet.maintain())
      {
        case 1:
          //renewed fail
          Serial.println("Error: renewed fail");
          break;

        case 2:
          //renewed success
          Serial.println("Renewed success");

          //print your local IP address:
          printIPAddress();
          break;

        case 3:
          //rebind fail
          Serial.println("Error: rebind fail");
          break;

        case 4:
          //rebind success
          Serial.println("Rebind success");

          //print your local IP address:
          printIPAddress();
          break;

        default:
          //nothing happened
          break;

      }
    }

    void printIPAddress()
    {
      Serial.print("My IP address: ");
      for (byte thisByte = 0; thisByte < 4; thisByte++) {
        // print the value of each byte of the IP address:
        Serial.print(Ethernet.localIP()[thisByte], DEC);
        Serial.print(".");
      }

      Serial.println();
    }

The situation is similar to https://arduino.stackexchange.com/questions/9362/ethernet-shield-not-getting-ip, but I checked that all pins are connected properly. Also setting pin 10 to high does not change anything.

body:
> Note that because the W5100 and SD card share the SPI bus, only one
> can be active at a time. If you are using both peripherals in your
> program, this should be taken care of by the corresponding libraries.
> If you're not using one of the peripherals in your program, however,
> you'll need to explicitly deselect it. To do this with the SD card,
> set pin 4 as an output and write a high to it. For the W5100, set
> digital pin 10 as a high output.

Ref. https://www.arduino.cc/en/Main/ArduinoEthernetShield


body:
I found the solution in [modrego's answer on Arduino Ethernet Shield 2 stuck on EthernetServer::begin()](https://arduino.stackexchange.com/a/13907/26916). I need the **Ethernet2** library for the W5500 Ethernet controller. The Ethernet library is for W5100 only.

This library is not included with the arduino.cc library(as of IDE version 1.6.12 and older, this will likely change in future versions). I had to install it. You can do this by:

 1. **Sketch > Include Library > Manager Libraries...**
 2. Type "ethernet2" in the **Filter your search...** field
 3. Click on the **Ethernet2** entry.
 4. Click the **Install** button.
 5. Click the **Close** button.

You will need to change the line:

    #include <Ethernet.h>
to:

    #include <Ethernet2.h>
Other files included in example sketches for the Ethernet library will need similar modifications.


message:
All of the sudden the Nano will not accept programming

I have been working merrily along with CH340 to make Com10 work.  It has been working flawlessly but now I am getting various messages like it can't open the port then the programmer is not responding.  It tries several times before giving up.

This was working fine yesterday.

I tried uploading to a raw board not connecting to anything and am getting the same result.

Suggestions?

body:
This problem occurs quite often with all the boards. Here is how to troubleshoot it.

1 - Unplug the Arduino.

2 - Upload the program **WITHOUT** any boards connected to your computer.

3 - Replug your Arduino.

4 - Upload the program **WITH** your Arduino connected to your PC.

[If this doesn't work, read this post by Nick Gammon.][1]

  [1]: https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board


body:
OK, problem solved.  I wish I knew enough to be able to say why it worked, but here is what did the trick:

I uninstalled the IDE.
THEN REBOOTED.
Then installed the IDE (version 1.6.10) again, this time not selecting the USB driver.
THEN REBOOTED.

In Device manager it still shows the CH340 driver on COM14

All my sketches and the two libraries (DHT and LCD) in the documents/Arduino directory were unaffected.

And now it will upload to my boards just fine.

This is one of those times where I can't explain why, but I can tell you for sure that it worked for me.  I had tried uninstalling/reinstalling, but without the rebooting in between.  Perhaps that was the crucial step that needed to be taken.


message:
The Mysterious Case of the Mostly-Vegetable Servo

Story:
-

I was playing around with my Uno along with a servo.

To my stupidity (or more appropriately: ignorance), I set the voltage to my servo with `analogWrite()`, rather than `servo.write()`. It worked for a bit; but once it reached it's limit, it kept trying to move, to no avail.

Realizing what I had done, I pull the power source from my Uno.

Then, I went to change the code, and tested my servo once more.

The servo's casing is transparent (there is a sticker blocking the motor and circuit; but I can see 4 of the gears).

The bottom 2 gears are ticking ever so slightly (and the top 2 even less so), resulting in the propeller to move at most 5 degrees. At this threshold, none of the mentioned gears are ticking, but something is heard (probably a whirring gear not in sight).

At this point, I would've come to the conclusion that a tooth of the third gear had broken.

However, after I pull the power plug and put it back in, it spins (backwards) into it's initial position and begins the process mentioned above again.

---

Mystery:
-

Is my servo indeed broken?

What's not functioning correctly?

**Can it easily be repaired?**

body:
>Is my servo indeed broken?

Yes.

---
>What's not functioning correctly?

As you said, some of the gears must have shifted in some way hindering the smooth mouvement of the servo or making it simply not working correctly.

---

>Can it easily be repaired?

Well, it depends on you. Do you like repairing EXTREMELY small things? Are you skilled at that. I would say no, because it requires a lot of knowlage on the servo to be able to remove it, fix it, and not to forget, replace it into its original case. Simply buying a new one is quite cheaper and simpler.


message:
How fast can I drive a stepper motor?

I have a 28BYJ 48, 5V stepper motor. After some trial and error I got it working with the all the sample examples in Arduino IDE.

However when I increase the speed of the motor using setSpeed() beyond 15, the motor stopped rotating. Following is the configuration in which I am running the motor.

    const int stepsPerRevolution = 2048;
    Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
    myStepper.setSpeed(15);

I wanted to understand what factors limit the speed. And how fast can I rotate this motor?

Thanks,

Manish

body:
*"I wanted to understand what factors limit the speed. And how fast can I rotate this motor?"*
Read through the data sheet for your motor-the answers are there. Each different motor has its own data sheet. This will require some work on your part to find the data sheet and the info from it you require. Which can be used to deduce the answer your question.