text:
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!
   // 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);**

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

ok so that didn't work, I switched the wire from pin 2 to pin 3 and updated the attachInterrupt part. It still doesn't work and just says "Initializing I2C devices". I don't know why it isnt working! maybe something else in the program?

Did you switch the wire and change the code at the same time?  You should only do one of those.

ok so I tried it all and still doesnt work. I changed the pin and used original code, didn't work. I didnt change the pin and modified the code and it didnt work. I don't know whats wrong and why it doesn't work. It just keeps saying "Initializing I2C devices" and it doesn't doesnt work. I noticed though that when I have the Interrupt wire on pin 2 and with the modified code, it just says " initializing I2C" but then when I take the connect out of pin 2 it then says to press any letter to start. I think its something in the code i dont know. Anymore ideas what could be the problem?

You've got me then.  Try switching the sda and scl lines?  Try using 4.7kohm pullup resisters on each of those lines (resister goes between that line and 5v)?  Check to make sure the imu is correctly powered?  Finally I might delete the first 7 lines of the setup function and replace it with:
Wire.begin();
TWBR = 24;

yah I keep testing the mpu-6050 with the arduino uno and micro. It always works with the uno but just keeps " initializing I2C devices" on the micro. Could there be something else besides the attachInterrupt() that could not be allowing it to run with the micro?

Hey so I was looking through the pin-mapping of the micro and it says that  pin 2/SDA and pin 3(PWM)/SCL. I put the link of the mico pin-mapping and it seems that maybe pin 2 and 3 are perhaps interfering. Is it possible to change the code to another interrupt outside of pin 2 and 3? https://www.arduino.cc/en/uploads/Main/ArduinoMicro_Pinout3.png

I put on pin 7 for interrupt and the serial monitor now says "Initializing I2C devices" then says "Testing Device connections" then states "MPU6050 connection failed" then says "Send any character to begin DMP programming and demo:".   So aready by changing to pin 7 it seems to run something vs when I put it on pin 2 or 3 it just says " initializing I2C devices". What do you think? I am I going in the right path?

Yes, you are on the right path.  The Micro has interrupts on pins 0, 1, 2, 3, and 7.  SDA is now pin 2 and SCL is now pin 3.  I had been assuming that you were using the correct SDA and SCL pins but were you still using pins 4 and 5?  If you are currently using pins 2 and 3 for I2C and pin 7 for the interrupt then I have no idea why it isn't connecting.

YES!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! IT WORKSSSSS I LOVE YOU!!!!...thanks

actually I just checked and now the program stops running after 10 seconds. Is there something else I should be doing so it runs until I tell it to stop running?

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

Welcome to the Arduino SE community. Can you please edit your answer to provide more detail? Thanks.

Can you provide an example or a code snippet, to show where the change needs to be. As it stands, your answer is rather terse.

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

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

Run it and let it wait for 10 seconds.
Add while(!Serial); right after Serial.begin(115200);.
Set the baud rate to 115200. It works better in my opinion.
Any other devices connected to your I2C constellation? If yes, remove all for testing purposes
If it still doesn't work, reboot your PC.

ok so I tried that and it still doesn't work. It has been almost 30mins where it just says "Initializing I2C devices". I rebooted my computer and re-uploaded the program and it keeps giving me that. Also the "while(!serial);" already exists after the "serial.begin(115200);". I don't know why it isn't working still.

Post your code, it might be time for some surgery!

I took the code that was given in the link I put on my original post. Also how do I post my code on here? I'm new to this

Just copy paste, I'll edit it for you.

it says I need 10 reputations to have another post. Also when I copy and paste onto this box the code goes over the character limit. Is there somehow I can send it to you?

Edit the question. Paste your code. Select you whole code. Use this function {}in the question/answer editor.

yah thats exactly what I did and it says I need 10 reputations to post it. Is there some different way I can get you the code?

hey I was finally allowed to post the program


text:
The use of 4.7kOhm resistor with DS18B20 temperature sensor
I was using a temperature sensor DS18B20 with Arduino.
I've read 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?

Datasheet says?

Here is an interesting blog on the subject https://wp.josh.com/2014/06/23/no-external-pull-up-needed-for-ds18b20-temp-sensor/

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.

Note that while a resistor is required, it need not be 4.7kohm.  The internal resistors on the arduino are enough to drive 4 sensors at 2-3 feet of wire, not in parasitic mode.  The 4.7k resistor lets you drive systems with much higher capacitance (dozens of sensors at multiple meters).  For playing around or a single sensor, there really is no need.

Here you can find a more in-depth look at this question and why the internal pull-up can very well work. https://wp.josh.com/2014/06/23/no-external-pull-up-needed-for-ds18b20-temp-sensor/

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.

Thanks! What I still don't understand, is that we do supply the power to the temperature sensor by the 5V line directly (one of the legs of the sensor is conntected to the Arduino's 5V). So, does that mean that the power supply goes from 5V, through the resistor to the digital input line (the middle leg)?

How do you think the sensor works when its powered from the arduino?

Im trying to understand what you are thinking thats why I asked that.

In your particular use-case, you aren't using the parasitic-power feature. The 4.7k ohm resistor is a "pull-up" resistor for the bus's data line. Why 4.7k? At 5V, the most current that can flow through the resistor is about 1mA. That's weak enough that all any other device on the bus needs to do to bring the line down to (near) 0V is sink more than 1mA of current. But when that device let's go (stops sinking current) the line always rises back to 5V.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
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)?

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.

so conversely (and for my own understanding), to use these pins as a digital pin (which they are also capable of) I can also do a digitalRead(8)? Furthermore, is the 'A' required? I've read that it automatically assigns A if its an analogRead.

When referring to the pin in a digital context you can use either label.

If A8 equals 8 then they are interchangeable. If not, then not.

I guess I just found it strange that one pin could be used both as analog and as a digital!

I just looked the file up - you cannot use 8, you have to use A8 or 26.

Good to know. I'll have to look at the pins_arduino file for future ref!

What are those pin numbers followed by ; ?

Yes, they are followed by ;

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


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

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

Or you could try just appending a line terminator when sending the number.

Unrelated, but why include accelstepper 3x?

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:

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

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

can you  make line terminator on the code because Iam very new to arduino programing please and what I use if replace the parseInt():

how to terminate the serial


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

I have followed this tutorial: Tutorial ESP8266
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.
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

Why are you trying to upload code to a board without a chip? And where did that tutorial say to use software serial on hardware serial pins? It doesn't seem like you followed that tutorial at all.

No I plugged it at digital pin 8 and 9 instead of rx and tx. And is it not nessecary to remove the chip?

You can't upload a program to a chip, if it's not there.

@gre_gor - He doesn't want to upload a program into ATmega328 but is trying to upload the program into ESP8266 using the Arduino's onboard USB --> RS232 IC. In that case ATmega328 has to be either removed or held under reset and the connection between Arduino board and ESP8266 must be TX to TX and RX to RX. Se my detailed explanation here.

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.

I did put the chip back and switched the 0,1 pins to 8 and 9 but when I run the code it doesn't print ready..

@Beginnerprogrammer you are printing ready back to the ESP8266 not to the PC.

No, ATmega328 has to be either removed or held under reset and TX to TX&RX to RX is OK. See my comment under the question.

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.

That is not the case, TX to TX&RX to RX in this case is OK. See my comment under the question.


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

Indent your code with ordinary spaces, not with no-break spaces.

As Gerben notes, the stackoverflow question error: stray '\302' in program 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.

I retyped my code on a new sketch and it uploaded successfully but i tried to change the times to see if my RTC code uploaded accurately instead of just successfully  I tried changing the numbers on wake hours and minutes and now i have a compiling error.

The error message will have a line number that points you to (or near) the line causing an error.  If the error is in one of the uint8_t wake_HOUR1 = 12; ... uint8_t wake_MINUTE2 = 30; lines, it probably is a simple typo, like an extra or missing character.  Each of those lines should be of the form uint8_t somevariablename=somevalue; where somevalue should be an integer, like 0, 1, ... 7, 8, 9, 10, 11 ... 59.  A value expressed as 08 or 09 instead of 8 or 9 would produce an error because 8 and 9 are not octal digits.  A missing semicolon or no space after uint8_t also is an error.


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

What might the problem be?

I have included software serial library

Did you try changing the baud rate on software serial?

Unfortunately your image has been shrunk so much that I can't make out what it says.

I tried using 57600 baud rate

Even changed the serial monitor setting below to carriage return also

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


text:
ESP-12f SoftwareSerial read fails
I am trying to use esp8266 version of SoftwareSerial,  espsoftwareserial, on an esp-12f.
If I initialize an object using:
SoftwareSerial gpsSer(14,12, false, 256);

or
SoftwareSerial gpsSer(12,14, false, 256)

then gpsSer.write works in all both cases, using ports 12 and 14 for transmit appropriately,  but gps.read fails.
I would be grateful for any advice.
Paul

have you tried to use it with another serial device? You can even try to link it  to the hardware RX TX of esp to see if it behaves as expected.

Impossible to answer without seeing the full code.

The sketch works fine if i use the hardware TX, RX I only use the RX port from the ESP to read the output of a GPS device which produces about 200 bytes per second


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

Write the function calls one after the other, each terminated with a semicolon, like: first_function(); second_function();

This was my first attempt which also gives the same result, they run at the same time. Which I don't want, I want to run one after the other.

“they run at the same time”. No, they don't. They run one after the other. You are misinterpreting the symptoms you see: the Arduino runs a single thread of execution, with no provisions for parallelism.

Your very complicated loop function looks to me the same as: while (true) fade_red(1);

@Edgar Bonet Yes, I know it's not intel multithreaded processor. I know it does 1 fetch and 1 execute every cycle. Of course there's no parallelism in processing. The Atmega 328p actually runs them simultaneously which updates each function so fast. It doesn't run one function and waits for it to finish.

@Nick Gammon Why my loops are very complicated? I'm trying to do as much simple code as I can with true C. If you have any suggestions for improving my code tell me, I would like to learn new techniques :)

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.

Thank you for your suggestion. And yes your guessing is right I want to perform each one at a time. And I don't want to code with Arduino coding style, that's why I switched to true C coding. And thanks for the provided code I think I learned something here, you wrote one function for fading! Interesting :)

OK, I tested your code and it actually does very similar to my previous code, it also mixes the colors in more beautiful way :)

@PerchEagle the "Arduino coding style" is true C/C++ code. The Arduino platform developers have just used function wrappers to make everything easier to read. See https://en.wikipedia.org/wiki/Wrapper_function

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.

Yes as I mentioned I tried switch case, do while, if and while loops. All the same result. The code you provided would also be the same, because the MCU starts the first function and not wait for it to finish and go to the second function and starts it as well. So the fading does altogether which is another methodology I would prefer as mixing the colors, but now I want to run each function as a complete fade then starts the second function. I want to learn this skill in C.

because the MCU starts the first function and not wait for it to finish - well it does wait for it to finish so your observations are flawed. What you think is happening just isn't.

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

Yes, you are correct! OK I have to look for another solution. I looked into pointers, can I connect a pointer to a SFR; like, OCRnA or OCRnB? I tried but didn't work.

Yes you can, but I'm curious to know why you want to.

Because I want to merge two functions which are the red and green fade functions which control SFRs. So I want to design one function which has a pointer to deal with 2 SFRs so as I choose a specific color there are assignments for each OCR.

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

Thank you very much for the help but they still somehow run together! It's little improved from my code.

try adding in a function that nofade or turn off to make it more readable

so at least you will know it turns off -you should be able to fix it from there

OK, I think I have to add a different function in between the two functions! Sounds a good idea :) But also I think it would be the same, that the microcontroller would run them all in parallel where I want to achieve the sequential methodology.

using the inbetweeen idea is correct -it wwill work if you code it correctly

yabbadabba, edit your answer; highlight the code with mouse (or by placing cursor at start of code, and holding down shift while moving cursor to end of code); then press ctrl-K or click the {} icon in edit tools bar.  This marks the code as code and makes it visible as code

@jwpat7 so that how you do it-thanks-i learned something very useful

After I added serial functions, it runs so fast, after I added serial.print(counting variable) it shows the counting actually goes well where it counts 1, 2 and 3 then resets as I wanted but the MCU actually does that all together.

Post your updated code if you want to-so I can see exactly what you mean

and arduino uno MCU cant do parallel function calls as you seem to be implying

Of course not parallel as multithreading I know, I mean that the MCU does the functions so fast together, it does the counting and the fading altogether, as it counts and updates the registers of the PWM very fast and simultaneously.

Code updated. It still the same code I just added serial function in the middle.

Let us continue this discussion in chat.

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

I don't understand why you are altering an internal timer's "compare" value like that. I'm not sure that will even have any effect, as the timer will be in PWM mode, counting up to 255 anyway.

What you mean exactly? Because I must count the OCR because they are the SFRs which produce the PWM effect.

SFR = Special Function Register, I gather. I see. Wouldn't just doing analogWrite be a lot easier to read? Comparing if (OCR0A == 255) like that has a chance you will miss that exact number and have to wait for another cycle.

I don't want to program with Arduino coding style, I want to work with true C. The comparison works OK, there's no miss in my configuration until now.

I see. Well I was wrong about the comparison. OCR0A won't change unless you change it.

I think you meant the counter which changes all the time.

Aye, that I did. :)


text:
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 with the Uno and Wi-Fi shield - and how to search for them?

You may even ask adafruit support (they are pretty good at support). But, because of the possibility of having multiple shields use the same pins, I don't use shields.

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!

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

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.


text:
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. I tried this solution but only device address with 0x00 is working.
The question is what device address should I use for additional chip?

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

I share my solution with 7 MCP23017 chip , 7x14 pins=98 pins using adafruit library.
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

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


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

Your question isn't clear about how many meters are involved, what you want to measure or find out, or the source of whatever it is you want to measure.  Explain better, and include a schematic if possible.  (You can draw a schematic by clicking the Schematic icon on the editing toolbar)

I have only one smart meter, this meter has a pulse output. what I want is counting the pulses of my meter using the Arduino. Now, my problem is the output voltage of my meter is varying. In addition, to connect my pulse output to the Arduino the output voltage should be stable and = 5V. Therefore, my question is how can I make the voltage stable since it's varying? (please see my circuit diagram I updated my question)

What is it varying between?

it's varying between 1V to 17V approximately

How about using an optocoupler? http://www.electronics-tutorials.ws/blog/optocoupler.html This would isolate the two circuits.

the Arduino is accepte only a stable voltage (5V). if so, get a real Arduino: a real arduino allows you to accept a logic 0 or a logic 1 and anything in between.

Your schematic contradicts your question: The question implies a voltage output from the meter, whereas the schematic shows the output as being electrically equivalent to a switch. Please clarify.

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

simulate this circuit – Schematic created using CircuitLab
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.)

Thank you so much for that great answer!! So, if my voltage is still varying but in the range of 1 to 5V I still can connect it to the Arduino?

@fahd, right.  The resistor ratio shown will divide 17 volts down to about 4.6V.  Input voltages higher than 0.6*Vcc  (ie, 3V on a 5V system) are read as 1's, per Table 30-1. Common DC characteristics on page 313 of ATmega328 specs.  The absolute max voltage on any Pin except RESET is Vcc+0.5V, or 5.5V on a 5V system, so 4.6V is an ok input level.

If your pulse low-voltage is 1V, the divider will divide that down to 0.27V, which is adequately below 0.3*Vcc, or 1.5V on a 5V system, to read as a 0.

Can you be more specific on Vlow and Vhigh of the pulses? I would suppose that Vlow is always 0, and that the crest of the pulses can vary between 1 and 17V. Is that the case? That's quite different than when Vlow is 1V and Vhigh is 17V.

If, as I read it, the meter's output pulses between 0 for LOW, and [1v - 17v] for HIGH, then the signal will need to be conditioned by Schmidt trigger to bring pulses less than the MCU's minimum input HIGH level (~2v) up to something higher than than that level, to ensure they will be read as HIGH.

@JRobert, yes, a comparator would be needed in that case.  But because Fahd hasn't answered kxtronic's question about Vlow and Vhigh and hasn't provided a meter spec or part number, I'm going to leave my answer as it is.


text:
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() {
}

I doubt that baud rate is the problem.  You might be overflowing a buffer, however.  Nobody here can say for sure without seeing the actual code.  Edit question, paste in the code, highlight it, and press ctrl-K to mark the code as code

If you have a MEGA then why use SoftwareSerial? Use one of the several available HardWare UARTpresent on the chip instead.

Don't use delays in serial code.  If you want intact messages, your program will need to collect data until you find something that defines their end, like a newline.  Bluetooth is going to be packetized so your data will likely be bursty - a bunch of characters then some time before any more.  You'll need to consider the burst boundaries arbitrary, what matters instead are the end conditions (newline or whatever) within your data.  Those could even occur in the middle of a burst.

Well the sensor I use has a sampling rate of 8Hz so every 125ms it will sample and send a string, thats the reason behind the delay(). I wasn't using it before and it would either give me trash or nothing, so should i use while(!Serial1.available()) since I need to be sure there is something there.

Your code should be event driven, not delay driven.  As already explained the arrival time and grouping of data after the bluetooth will not be regular or meaningful.  Your code needs to look for a condition within the data, such as a newline or other end marker, or else your code needs to not care where one message ends and another starts, deferring that to something else (human, another program yet to be mentioned, etc)

Thanks @ChrisStratton, I was able to fix it by making it more event driven but now there is an other problem. I need to write the strings to a .txt file in an SD card, but if I try to do it in that while receiving the strings it causes the same previous problem. So it has to be stored in an array to be written after I've received all the strings, but the array needs to be at least 480 in size. When I tried this nothing was written in the .txt file, it's probably a memory leak. Any thought on how to fix this? Should I make a new thread?

I think it would be better if you post your "another problem" as an another question, considering the original question is answered.

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.

Though this is not the problem.

I agree but that's the question he asked.

Then what is the problem?

The actual issues are already explained in comments on the question; basically a complete misimplementation of serial data handling.


text:
Ethernet module ENC28C60 doesn't connect to internet when DHCP on router is disabled.
Update: Examples from library are working if DHCP is enabled!
Using this library I try to connect with static IP but it always say DNS failed. Ethernet module is blinking that means is good connection also static ip is correct..
Question: What is hisip and how can this module connect to internet with static IP`?
Connections :
VCC -   3.3V
GND -    GND
SCK - Pin 52
SO  - Pin 50
SI  - Pin 51
CS  - Pin 53 # Selectable with the ether.begin() function

Code:
// This demo does web requests via DNS lookup, using a fixed gateway.
// 2010-11-27 <jc@wippler.nl> http://opensource.org/licenses/mit-license.php

#include <EtherCard.h>

#define REQUEST_RATE 5000 // milliseconds

// ethernet interface mac address
static byte mymac[] = { 0x74, 0x69, 0x69, 0x2D, 0x30, 0x31 };
// ethernet interface ip address
static byte myip[] = { XXX, XXX, 216, 199 };
static byte gwip[] = { XXX, XXX, 216, 126 };
static byte dnsip[] = { 8, 8, 8, 8 };
// remote website name
const char website[] PROGMEM = "google.com";

byte Ethernet::buffer[300];   // a very small tcp/ip buffer is enough here
static long timer;

// called when the client request is complete
static void my_result_cb (byte status, word off, word len) {
  Serial.print("<<< reply ");
  Serial.print(millis() - timer);
  Serial.println(" ms");
  Serial.println((const char*) Ethernet::buffer + off);
}

void setup () {
  Serial.begin(57600);
  Serial.println("\n[getViaDNS]");

  if (ether.begin(sizeof Ethernet::buffer, mymac, 53) == 0)
    Serial.println( "Failed to access Ethernet controller");

  ether.staticSetup(myip, gwip);

  if (!ether.dnsLookup(website))
  Serial.println("DNS failed");
  ether.printIp("Hisip: ", ether.hisip);
  ether.printIp("Myip: ", ether.myip);
  ether.printIp("Gateway: ", ether.gwip);
  ether.printIp("DNS: ", ether.dnsip);

  timer = - REQUEST_RATE; // start timing out right away
}

void loop () {
  ether.packetLoop(ether.packetReceive());

  if (millis() > timer + REQUEST_RATE) {
    timer = millis();
    Serial.println("\n>>> REQ");
    ether.browseUrl(PSTR("/foo/"), "bar", website, my_result_cb);
  }
}

Output:
[getViaDNS]
DNS failed
Hisip: 0.0.0.0
Myip: XXX.XXX.XXX.199
Gateway: XXX.XXX.216.126
DNS: 8.8.8.8

>>> REQ

>>> REQ
...


text:
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
  }
}

Hi, welcome to Arduino.SX. You can use { } on top of the editor bar to mark you code so they all become readable between text and codes.

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


text:
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!

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.

Thank you for your response. I have amended my code and replaced the loops that are next to each other with a differently declared int variable. However, it seems that the program still waits for the for loops to execute finish before transiting to the allocated function (looper4, looper5).

It does look very much like you have infinite recursion going on there. Looper1 calls looper5, looper5 calls looper1, looper1 calls looper5, etc. I think you need to re-think your program design completely - maybe consider using a Finite State Machine instead of all these loops calling functions calling functions calling functions calling .... etc

At the moment it's in effect like you're asleep dreaming that you're asleep having a dream about being asleep and dreaming that you are asleep, etc... When you wake up (if you ever do) how do you know you have really woken up and not still in a dream?


text:
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. 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?

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.

This was perfect!

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.

I  think the OP was asking can he get a chip on a breakout board -or something that can be interfaced to an 8 bit arduino-rather  than an IC chip.

Yes, agreed.  I debated on answering or commenting.  But this is the Arduino bit of stackexchange and I thought the information useful not just for the OP but for others exploring using the same chip.

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.

@Manjenko Thank you. That helped me understand why it is retired. But is there a substitution for it that would work with this?

Yes, it's called don't use that, use something better. Maybe a Teensy 3.1 or something like that...?

Please don't be rude. Also, I already bought that because I thought people on StackExchange could help me.

I'm not being rude. I'm being serious. 8 bitters have a role, but that role is not working with audio. Teensy's are very similar in design and price but have much more power and are more suited to audio work.

Dat Han Bag's answer worked.


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

SPI devices communicate in full duplex mode. Cant you use other interfaces that use less wires in their standard?

Switching it to an input should disconnect it from SPI. Otherwise, it will be MOSI.

You could always use bitbanging in the form of shiftIn.

@IgnacioVazquez-Abrams That would be a good solution if I wanted to use the MOSI pin as an input. However, I require it to be an output.

@Gerben That looks viable. But I worry that it might not be as reliable as the hardware implementation.

The SPI feature varies on different processors.  The Arduino Pro Mini uses a ATmega328.  Either you need to download the appropriate SPI (and other) libraries from github and alter them - or read the ATmega328 chip spec.  It may be you can control the ATmega328 MOSI pin by simply using the pinmode() call and defining it as an output like you want.  Or you may be stuck in a situation where the ATmega328 is either in SPI mode and controlling all SPI pins or not in SPI mode and letting you control all SPI pins.

@st2000: I guess I'll just have to do some experimenting and see what works and what doesn't.

@yabbadabba: Yes, as Gerben already recommended. Could possibly be a solution.

The hardware features are so nice, because they're implemented in hardware. Theoretically, it would require changing the hardware itself. If you really need one extra pin, you could use an I/O expander (SPI or I2C) or a bigger chip.

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.

This solution worked for me.  I wanted to use the MISO pin for DC on a SSD1331 display.  I privately modified the AdaFruit library constructor to call pinMode after SPI.begin() and it worked.

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.


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

@yabbadabba - comments under questions are for seeking clarification about the question. Not for stating that your answer is the best one. People will vote for answers that they think are good, including yours, if they merit such votes. Your comments have been deleted.

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:

more information at
wheel Encoder
another encoder

If the OP make their own hand built encoder then how do they know how accurate it is?

@yabbadabba, if the OP makes his own hand built encoder, he will know the number of openings in the wheel. He will be able to count the number of openings and measure the distance that the wheel travels, or simply perform the math of circumference equals pi times the diameter.

@fred_dot_u I think what your saying is likely to be  true if he makes it with a CNC machine

There's a fellow on YouTube (HomoFaciens) who makes amazing constructions with ordinary tools. His encoder wheel is cut out of sheet metal or cardboard depending on the device he's building. The slots are cut with scissors or metal shears and are mildly irregular, yet provide fractional control of the device. The founding principles of the physics of the encoder wheel care not about the sophistication of the construction. One can turn a bicycle wheel into an encoder, which happens to be how bicycle speedometers work! So many answers, so few characters.

@fred_dot_u    " (HomoFaciens) who makes amazing constructions with ordinary tools"- sounds like he's got a rare talent

One of his talents is his skill at presenting material for the benefit of so many, to make this sort of thing (encoding, in this case) easier to understand and to implement in one's own projects. As an example specific to this project, the OP could use or add toy wheels with spokes and install an optical sensor to trigger on the spokes. That would qualify as a hand-built encoder and the OP could count the spokes. The diameter and circumference can be measured as well. The OP's satisfaction can be gained by implementing something from materials on-hand (purchased) rather than CNC created.

@fred_dot_u " (HomoFaciens) who makes amazing constructions with ordinary tools"-there's a video of him building a rotary encoder- doesnt seem to use a toy wheel though. There's different ways to make , hand made, the encoder-by using print out on paper as it says in this answer

Guys guys. No need to use any tools. Print the graphichs on a photocopy paper and attached it on the wheel. Like in second link. Thanks but its 3 am n i feel so sleepy.

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

how do you determine the accuracy of the hand built rotary encoder?

@yabbadabba - the ultimate accuracy mostly comes from accurately knowing the distance traveled per revolution of the wheel, for example you can measure over long distances, but you have to worry about slipping and straightness of path.  There can also be issues with regularity of spacing and eccentricity of the pattern relative to the shaft (or the wheel itself relative to the axle) but while those are serious concerns in say, a CNC machine tool, with moderate care they will probably not be problematic in a maze robot.

@ChrisStratton "probably not be problematic in a maze robot". Its not clear to me too-if it would definitely be a problem

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

If they go down the route of interfacing to USB mouse directly to ATMEGA then they need a USB host solution-  this has already been done (mainly in software)-see https://courses.cit.cornell.edu/ee476/FinalProjects/s2007/blh36_cdl28_dct23/blh36_cdl28_dct23/

An old PS2 mouse is easier to interface to Arduino.  There is documentation and library at http://playground.arduino.cc/ComponentLib/Ps2mouse

Obviously that depends on if OP has ps2 mouse , USB mouse is more common. For the USB  related  link I gave the hardware part I would say are easier to get.

@sa_leinad, your suggestion is sound. The type of mouse is not as important if one is willing to dissect to a board level. I've dissected a mouse to use the spoked wheel inside which has a properly aligned optical trigger pair, along with the plastic structure to keep things in place. Counting pulses and direction over a known course, with the appropriate math would serve as a useful distance measuring device. Discarded printers also contain linear and rotary encoders with opto-pairs, but harder to use in a robot!

@fred_dot_u has brought up a good point - if you can get your hands on some of the really old mice that have the ball inside (instead of the red optical sensor) there are two quadrature encoders (slotted wheel and optical sensor, one from the x direction and the other from the y direction) that can be harvested from the mouse.

In modern mice, there is a quadrature encoder in the scroll wheel. Here are some links on how to harvest the encoders: http://www.seattlerobotics.org/encoder/200311/johnson/Mousebot.html http://www.boondog.com/tutorials/mouse/mouseHackBeforeWeb.htm

@sa_leinad, the funny thing about your reply to my comment was that I was referring to the mouse wheel and was ambiguous in my description. I have three mouse wheels harvested with the circuit board and mouse housing. By keeping the parts together, it allows easy access for wiring and mechanical placement too. The unwanted portions can be cut free, reducing the size of the bundle to be installed, while the solder pads on the circuit boards facilitate the wiring. Your link is very supportive of the OP's purpose.


text:
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 Ethernet shield not getting IP, but I checked that all pins are connected properly. Also setting pin 10 to high does not change anything.

Which Ethernet controller chip does your Ethernet Shield have? The common ones are W5100, W5200 and W5500.

It is the W5500

Check out the same issue here.

This happens when the network isn't bridged. You can check this link here

I found the solution in modrego's answer on Arduino Ethernet Shield 2 stuck on EthernetServer::begin(). 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:

Sketch > Include Library > Manager Libraries...
Type "ethernet2" in the Filter your search... field
Click on the Ethernet2 entry.
Click the Install button.
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.

Thanks, this is what I needed to do too. Doesn't really seem to be any official docs stating this.

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

I think the relevant documentation is: https://www.arduino.cc/en/Main/ArduinoEthernetShieldV2 . I tried setting 10 to LOW and 4 to HIGH, as well as the other way round, no effect. The documentation also says port 53 needs to be an output, but that does not have any influence either.


text:
How to set Alarms on the DS3231 easily so the Nano doesn't have to go to sleep with delay statements?
I want my solar array sun tracker to shut down at night then move full east in the morning to catch the first rays.
I know the DS3231 can set alarms but it is not clear from its documentation how to do it with the normal library.
Delay statements are the way I have it periodically check for when to take readings, but I really want it to be able to respond to radio-remote control commands, which don't work during delays.
Q:  Is there an easier way?

Which library are you using? As this one supports it just fine.

That is interesting.  Will bookmark it.  Thanks, @Gerben

https://arduino.stackexchange.com/questions/33972/how-to-have-some-code-executed-at-a-certain-time-of-day-with-a-ds3231-rtc/33973#33973

Here it is:
https://github.com/sleemanj/DS3231_Simple
Example:  https://github.com/sleemanj/DS3231_Simple/blob/master/examples/z2_Alarms/Alarm/Alarm.ino
This is what I was looking for.
My system needs to be able to respond to radio remote commands while asleep, and the long delay() statements were preventing that.
These alarms solve the problem.


text:
Attiny45 resets when setting digitalOutput to low
I currently try to program an Attiny45 with an Arduino UNO as ISP.
The Arduino is able to program the Attiny45.
However, when I try the blink example, it resets the Attiny, when setting digitalOutput to low
(on any pin)
To further confirm, that it resets only, when setting a pin to low, I wrote this sketch and let it run on the Attiny.
void setup() {
  pinMode(3, OUTPUT);
}

void loop() {
  delay(1000);
  digitalWrite(3, HIGH);
  delay(1000);
  digitalWrite(3, LOW);
  delay(10000);
  digitalWrite(3, HIGH);
  delay(1000);
  digitalWrite(3, LOW);
}

The LED I connected to pin 3 waits 1 second, and then turns on, but when 1 second passed and it should stay off for 10 seconds, it resets and only waits 1 second.
I tried reburning the bootloader onto the Attiny, which had no effect.

Could you show the wiring diagram?

I follwed these instructions

Including the 220Ω resistor with the LED as in the last step?

My LED can handle 5V, so I used it without, but that cant be the issue

That would be a very special LED then, if it can handle 5V without a resistor.

"Can handle" and "Is designed to work with" are two very different things. Chances are it can't handle it, but it's not getting it. Instead it is causing massive power droop from over current making the BOD trigger in the ATTiny.

If it would be the BOD, then how come that the attiny only resets, when setting the pin to low?

Ok it the resistor actually fixed it, but still. Why only when setting it to low?

Because the wiring shown there has the LED connected between the IO pin and +5V, so the IO pin, when switched LOW, turns the LED on by acting as ground.

Ok, but there I connected the LED frome the IO as output to Groud

Including the 220Ω resistor with the LED as in the last step?

...

My LED can handle 5V, so I used it without, but that cant be the issue

The one thing that "can't be the issue" is indeed the issue! Without a resistor the LED will attempt to conduct a lot of current which will damage both it and the output pin of the processor.
See The care and feeding of LEDs. From that page:

LEDs are not like normally electronic devices in that you can’t just apply a voltage to them and they work, they have to be fed the correct voltage and current to keep them happy.

And then:

There are several web sites and schematics on the web that suggest you can attach an LED directly to an Arduino output pin with no current limiting resistor. They are wrong, and following them will damage your Arduino.

So, by not using a resistor, when the output pin goes LOW it attempts to "sink" current, in order to turn on the LED. Since you have no resistor, it sinks as much as the output drivers can handle, dropping the supply voltage inside the Attiny, which then goes below the brownout level, and resets itself.
Please, when following a circuit, don't just omit bits of it, and then post a question about why it doesn't work. At least follow the circuit exactly, and then when you have learned more about electronics, you can start experimenting.

Where am I supposed to ask if not on a forum ment for it?

I searched more than enough times, so I think me asking would be totally valid.

I didn't say to not ask here, I said to follow the instructions first. You said "I followed these instructions" but you didn't. You left out part of them (the resistor). Nor did you say that in your question. You might have said "I followed the instructions but omitted the resistor which I didn't think was important".

Ok, that made more sense, then sorry if I seemed a little aggressive, and thank you :)