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

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.

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:
MPU-6050 + Arduino Micro + nRF24L01 FIFO overflow!
So I have an Arduino Micro, nRF24L01, and MPU-6050 all attached together and its transmitting information to another nRF24L01 on an Arduino Uno. The problem is that I keep getting FIFO overflow on the sending side. If I leave the sensor holding still it goes going for some time, but when I start moving the sensor around it halts, like it can't take that much data when the sensor is moving around. So I think its something with the code:
// Include libraries necessary for the radios
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

//set up name for serial communication of the radio
RF24 radio(9, 10);

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

// We are using this output to obtain global coordinate acceleration
//and euler angles (coordinate system irrelevant)
#define OUTPUT_READABLE_WORLDACCEL_AND_GYRO

// 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 = 12; // 400kHz I2C clock (200kHz if CPU is 8MHz). Comment this line if having compilation difficulties with TWBR.
    #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 Ardunio
    // 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 radio communication
    radio.begin();
    radio.setRetries(15, 15);
    radio.openWritingPipe(0xF0F0F0F0A1LL);

    radio.stopListening();

    Serial.begin(115200);

    // 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(54);
    mpu.setYGyroOffset(15);
    mpu.setZGyroOffset(33);
    mpu.setZAccelOffset(1613); // 1688 factory default for my test chip
    mpu.setXAccelOffset(-4009);
    mpu.setYAccelOffset(332);

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

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

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

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

    // configure LED for output
    pinMode(LED_PIN, OUTPUT);

}

// ================================================================
// ===                    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();
        char fifo_text[]="FIFO overflow!";
        radio.write(&fifo_text, sizeof(fifo_text));
        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_AND_GYRO
            // 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.print(aaWorld.z);
            //radio.write(&aaWorld.z,sizeof(aaWorld.z));
            //String x=String(aaWorld.x);
            //const char*text=x.c_str();

            /*
            char x_text[]="X acceleration";
            radio.write(&x_text, sizeof(x_text));
            */
            typedef struct Value {
              int x;
              int y;
              int z;
              int e0;
              int e1;
              int e2;
            } Value;

            Value value;

            value.x=aaWorld.x;
            value.y=aaWorld.y;
            value.z=aaWorld.z;

            /*
            float acceleration[3];
            acceleration[0]=aaWorld.x;
            acceleration[1]=aaWorld.y;

            char x_value[8];
            char y_value[8];

            dtostrf(aaWorld.x,5,2,x_value);
            dtostrf(aaWorld.y,5,2,y_value);
            //char* coordinates[]={x_value,y_value};
            //char* coordinates[]={x_value,y_value};
            int coordinates[]={aaWorld.x,aaWorld.y};
            //radio.write(&y_value, sizeof(y_value));
            //radio.write(&coordinates, sizeof(coordinates));
            */

            //Serial.println(aaWorld);
            mpu.dmpGetEuler(euler, &q);

            //Serial.print("euler\t");
            int euler_0=euler[0] * 180/M_PI;
            value.e0=euler_0;
            //Serial.print("\t");
            int euler_1=euler[1] * 180/M_PI;
            value.e1=euler_1;
            //Serial.print("\t");
            int euler_2=euler[2] * 180/M_PI;
            value.e2=euler_2;
            //euler=(int[3])euler;
            //int euler[]={1,2,3};
            //Serial.write(euler*180/M_PI,3);
            //delay(50);

            radio.write(&value, sizeof(value));
            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);
    }
}

Properly format your code.

I don't know why the code ended up like this

I found the problem, I had to comment out_put_readable_realaccel. So it had to be //#define OUTPUT_READABLE_REALACCEL because it was running the yaw pitch and roll and the real acceleration at the same time so it was overloading.
Posted on behalf of the OP.

source: Stack Exchange

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

sort: votes


text:
LEDs Randomly smooth transitioning, accounting for black or how-to switch using HSV
I am stuck trying to get it not to account for black in RGB.  My first instinct was to use the HSV color spectrum over the RGB rainbow but, the same code will behaves differently in HSV.  If i could get the same effect in HSV I would, and that would account for the black, but I have not found a solution for that or the accounting for black in RGB.  Here is my code:
#include <FastLED.h>

#define LED_COUNT     96
#define LED_OUT       13
#define BUTTON_IN     10
#define ANALOG_INPUT  A9
#define EXTRA_PIN_A    7
#define EXTRA_PIN_B   11

struct CRGB leds[LED_COUNT];

void setup() {
  Serial.begin(57600);
  LEDS.addLeds<WS2812B, LED_OUT, GRB>(leds, LED_COUNT);
  LEDS.show();
}

void colorLoop() {

  static int Col1;
  static int Col2;
  static int Col3;

  static int C1;
  static int C2;
  static int C3;

  if ((((Col1 == 0) || (Col1 == 250)) && (((Col2 == 0) || (Col2 == 250)) && ((Col3 == 0) || (Col3 == 250))))) {

    // select a random number from 1 to 2 for the array
    C1 = random(1, 3);
    C2 = random(1, 3);
    C3 = random(1, 3);
  }

  if (((C1 == 1) && (Col1 != 0))) {
    Col1 = (Col1 - 10);
  }
  if (((C2 == 1) && (Col2 != 0))) {
    Col2 = (Col2 - 10);
  }
  if (((C3 == 1) && (Col3 != 0))) {
    Col3 = (Col3 - 10);
  }

  if (((C1 == 2) && (Col1 != 250))) {
    Col1 = (Col1 + 10);
  }
  if (((C2 == 2) && (Col2 != 250))) {
    Col2 = (Col2 + 10);
  }
  if (((C3 == 2) && (Col3 != 250))) {
    Col3 = (Col3 + 10);
  }

  for (uint8_t i = 0; i < LED_COUNT; i++) {
    leds[i] = CRGB(Col1, Col2, Col3);
  }
  delay(100);
  LEDS.show();
}

void loop() {
  colorLoop();
}

Does your definition of black refers to all the LEDs off?

yes, RGB(0, 0, 0) displays the same as the option "off".

Black will basically be when all the colours have reduced to 0. That can only happen when all three of C1, C2 and C3 are 1. So you basically need to ensure that never happens.
And that is simple enough to arrange, with a "try again" construct:
if ((((Col1 == 0) || (Col1 == 250)) && (((Col2 == 0) || (Col2 == 250)) && ((Col3 == 0) || (Col3 == 250))))) {

    // select a random number from 1 to 2 for the C1,C2,C3 array
    do {
        C1 = random(1, 3);
        C2 = random(1, 3);
        C3 = random(1, 3);
    } while ((C1 == 1) && (C2 == 1) && (C3 == 1));
}

Pick three numbers. If they are all 1 then you are destined towards black. So go back and pick three new random numbers. Keep trying until you get at least one result that isn't 1.

nice approach @Majenko but, that would simply take away from the functionality.

How so? It gives you the same range of random numbers for the three values except it rules out getting 1,1,1 which would fade all the channels to black. It would give you 1,1,2 1,2,1 1,2,2 ... 2,2,2 but never 1,1,1

I found this approach works:
if (((Col1 <= 50) && ((Col2 <= 50) && (Col3 <= 50)))) {  //avoid black
   C1 = 2;
   C2 = 2;
   C3 = 2;
}

For it not to be black, at least one color (R,G,B) have to be on.
Before assigning the color values to the LED, maybe you can try using the constrain function to keep the values within a range. For example,
...

Col1 = constrain(Col1, 50, 150);  //If anything falls below 50, set it to the minimum value (50)
Col2 = constrain(Col2, 50, 150);
Col3 = constrain(Col3, 50, 150);

for (uint8_t i = 0; i < LED_COUNT; i++) {
   leds[i] = CRGB(Col1, Col2, Col3);
}

....

Sure enough! adding the constrain function to one of the static integers fixed the RGB from going to black. Now simply set 50 as the min value in the rest of the code:
void colorLoop() {
    //Set the minimum value to 50
    static int Col1 = constrain(Col1, 50, 255);
    static int Col2;
    static int Col3;

    static int C1;
    static int C2;
    static int C3;

    if ((((Col1 == 50) || (Col1 == 250)) && (((Col2 == 0) || (Col2 == 250)) && ((Col3 == 0) || (Col3 == 250))))) {

        // select a random number from 1 to 2 for the C1,C2,C3 array
        C1 = random(1, 3);
        C2 = random(1, 3);
        C3 = random(1, 3);
    }

    if (((C1 == 1) && (Col1 != 50))) {
        Col1 = (Col1 - 10);
    }
    if (((C2 == 1) && (Col2 != 0))) {
        Col2 = (Col2 - 10);
    }
    if (((C3 == 1) && (Col3 != 0))) {
        Col3 = (Col3 - 10);
    }
    if (((C1 == 2) && (Col1 != 250))) {
        Col1 = (Col1 + 10);
    }
    if (((C2 == 2) && (Col2 != 250))) {
        Col2 = (Col2 + 10);
    }
    if (((C3 == 2) && (Col3 != 250))) {
        Col3 = (Col3 + 10);
    }

    for (uint8_t i = 0; i < LED_COUNT; i++) {
        leds[i] = CRGB(Col1, Col2, Col3);
    }
    delay(100);
    LEDS.show();
}

great approach @Photon! however, using the constrain eliminates a lot of color possibilities.

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


text:
How to connect to pins when using I2C LCD shield?
How are pins used with this shield? The tutorial says that the header pins are inserted into the Arduino but the guide says they are not used for signals. Is there any way of using the other pins?

Update:

What it means is although all pins from the Arduino are connected only A4, A5 5V and Gnd are actually used by the shield.  I think that these 4 pins are shared with other shields and all the rest of the pins are available for shields to either share or use exclusively.
So, if you have this shield and an Ethernet shield, which needs exclusive access to pins d7, d8 and d9 then you would be to use both shields at the same time.

So it's not possible to use the other pins with this shield?

I think it is, I've edited the answer to make that clearer.


text:
Only one of 4 LEDs are lighting up
Before you ask - I've checked that the LEDs worked before putting them in my circuit. They all work.
I've connected 4 LEDs, shown in the arrangement below, up to my Adruino Lilypad. Pin 9 was used as the + 5V, the "- pin" was used as ground. In the schematic below, the "1" represents pin 9.

simulate this circuit – Schematic created using CircuitLab

When I start my sketch, I set pin 9 to high to check that all the LEDs are working. (this is a PWM pin so I write, analogWrite(9, 255);). At this point, only D5 lights up. If I connect up the two wires connecting R9-D6 and R10-D7, then both D5 and D8 light up... but never D7 or D6?
Doing some basic circuit calcs, the total resistance of the circuit is 100 Ohms (1 / (1 / (100 + 100)) + (1 / (100 + 100))). I'm powering from the usb connection to the computer so power source should be 5 V. Total current draw should therefore be 50 mA? Is that too much? If so, why does only D5 - or D5 and D8 when adjusting the circuit - light up?

you have 200 ohms in series with the LEDs .... remove one of the resistors in each leg

Those LEDs are 3.3V forward voltage. With two in series you need at least 6.6V to light them up.

...omg. So would it work if I put all 4 in parallel? Why did only 1 of 4 light up like that?

Not sure why one lights up. Some oddity maybe. Yes, using them in parallel is what you want to do.

Connecting 4 leds in parallel to a single output isn't advised, as it will exceed the maximum allow current. At most connect 2 leds in parallel to a digital output.

What would happen if I did exceed max current? I mean... I already have connected up in parallel & it's fine and works, but I still wanna be safe...! But no failsafe/fuse has kicked in...

The MOSFET in the GPIO pin will get hot, overheat, and go pop.


text:
GSM and NFC not working together
I have an Arduino Uno board, Seeed Studio NFC shield v2.1 and, an Arduino GSM shield stacked UNO -> NFC -> GSM, therefore, all the wires are going into pins in the GSM.
I have successfully created a program that measures various sensors on my attached breadboard and then prints them to serial and sends text depending on conditions. I have today added the NFC shield to the middle of the stack (so as to avoid unplugging all the pins in the GSM), now when I run any NFC program, the default ones provided on the serial I get the message "Didn't find PN53x board". However, if I unplug the GSM from on top of it the NFC programs run fine, reading and writing tags.
Is it just that the NFC and GSM will not work together or am I missing something.
Main code
// Include the GSM library
#include <GSM.h>

#define PINNUMBER ""

// initialize the library instance
GSM gsmAccess;
GSM_SMS sms;

int buttonPin = 13;
int buttonState = 0;
int buttonPressed = 0;
int trigPin = 11;
int echoPin = 12;
long duration, cm, inches;
int greenLED = 6;
int redLED = 8;
int buzzerPin = 10;

int pressurePin = A5;
int force;

const int inputPin = A0;
unsigned int inputSample;
const int inputWindow = 100;

void setup() {
  Serial.begin(9600);
  pinMode(buttonPin, INPUT);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);
  pinMode(buzzerPin, OUTPUT);
  pinMode(inputPin, INPUT);
  startUp();
  //setupText();

}

void loop() {
  button();
  delay(100);
  if (buttonPressed == 1)
  {
    pressure();
  }
  else if (buttonPressed == 2)
  {
    distance();
  }
  else if (buttonPressed == 3)
  {
    sound();
  }
  else if (buttonPressed == 4)
  {
    pressure();
    distance();
    sound();
  }
}

void sound()
{
  // two variables for minimum and maximum values in window
  unsigned int inputMax = 0;
  unsigned int inputMin = 1024;

  // loop for the window
  for (unsigned int i = 0; i < inputWindow; i++)
  {
    // read in a single value
    inputSample = analogRead(inputPin);
    // get the minimum and maximum value
    inputMin = min(inputMin, inputSample);
    inputMax = max(inputMax, inputSample);
  }
  // send the values on serial
  Serial.print("Min: ");
  Serial.print(inputMin);
  Serial.print("  Max: ");
  Serial.print(inputMax);
  Serial.print("  Diff: ");
  int Diff = inputMax - inputMin;
  Serial.print(Diff);
  Serial.println();
  if (Diff > 30)
  {
    alarm();
    sendText();
  }
  delay(250);
}

void pressure()
{
  force = analogRead(pressurePin);
  Serial.print("The force is: ");
  Serial.println(force);
  delay(250);
  if (force > 400)
  {
    alarm();
    sendText();
  }
}

void distance()
{
  digitalWrite(trigPin, LOW);
  delayMicroseconds(5);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);
  int echo = pulseIn(echoPin, HIGH);
  int trig = pulseIn(trigPin, HIGH);
  Serial.println(duration);
  Serial.println(echo);
  Serial.println(trig);
  cm = (duration/2) / 29.1;
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  delay(100);
  if (cm < 5)
  {
    alarm();
    sendText();
  }
}

void alarm()
{
  digitalWrite(redLED, HIGH);
  tone(buzzerPin,2500);
  delay(200);
  digitalWrite(redLED, LOW);
  noTone(buzzerPin);
  delay(200);
  digitalWrite(redLED, HIGH);
  tone(buzzerPin,300);
  delay(200);
  digitalWrite(redLED, LOW);
  noTone(buzzerPin);
  delay(200);
  digitalWrite(redLED, HIGH);
  tone(buzzerPin,2500);
  delay(200);
  digitalWrite(redLED, LOW);
  noTone(buzzerPin);
  delay(200);
  digitalWrite(redLED, HIGH);
  tone(buzzerPin,300);
  delay(200);
  digitalWrite(redLED, LOW);
  noTone(buzzerPin);
  delay(200);
  digitalWrite(redLED, HIGH);
  tone(buzzerPin,2500);
  delay(200);
  digitalWrite(redLED, LOW);
  noTone(buzzerPin);
  delay(200);
  digitalWrite(redLED, HIGH);
  tone(buzzerPin,300);
  delay(200);
  digitalWrite(redLED, LOW);
  noTone(buzzerPin);
  delay(200);
  digitalWrite(redLED, HIGH);
  tone(buzzerPin,2500);
  delay(200);
  digitalWrite(redLED, LOW);
  noTone(buzzerPin);
  delay(200);
  digitalWrite(redLED, HIGH);
  tone(buzzerPin,300);
  delay(200);
  digitalWrite(redLED, LOW);
  noTone(buzzerPin);
  delay(200);
  digitalWrite(redLED, HIGH);
  tone(buzzerPin,2500);
  delay(200);
  digitalWrite(redLED, LOW);
  noTone(buzzerPin);
  delay(200);
}

void button()
{

  buttonState = digitalRead(buttonPin);

  if (buttonState == HIGH)
  {
    buttonPressed ++;
    digitalWrite(greenLED, HIGH);
    noise();
    delay(2000);
    digitalWrite(greenLED, LOW);

  }

  Serial.println(buttonPressed);
}

void startUp()
{
  digitalWrite(greenLED, HIGH);
  noise();
  digitalWrite(greenLED, LOW);
  delay(500);
  digitalWrite(greenLED, HIGH);
  noise();
  digitalWrite(greenLED, LOW);
  delay(500);
  digitalWrite(greenLED, HIGH);
  noise();
  digitalWrite(greenLED, LOW);
  delay(500);
  loop();
}

void noise()
{
  tone(buzzerPin, 1000);
  delay(1000);
  noTone(buzzerPin);
}

void sendText()
{
    Serial.println("...");
    Serial.println("...");
    Serial.println("...");
    Serial.println("...");
    Serial.println("...");
    Serial.println("MESSAGE SENT");
    Serial.println("...");
    Serial.println("...");
    Serial.println("...");
    Serial.println("...");
    Serial.println("...");
    delay(4000);
//  char remoteNum[20];
//  Serial.println(remoteNum);
//  // sms text
//  char txtMsg[200];
//  Serial.println("SENDING");
//  Serial.println();
//  Serial.println("Message:");
//  Serial.println(txtMsg);
//
//  // send the message
//  sms.beginSMS("07123456789");
//  sms.print("HELP");
//  sms.endSMS();
//  Serial.println("\nCOMPLETE!\n");
}

void setupText()
{
  // initialize serial communications and wait for port to open:
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("SMS Messages Sender");

  // connection state
  boolean notConnected = true;

  // Start GSM shield
  // If your SIM has PIN, pass it as a parameter of begin() in quotes
  while (notConnected) {
    if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
      notConnected = false;
    } else {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  Serial.println("GSM initialized");
}

Code to be added when at a later date
#include <SPI.h>
    #include "PN532_SPI.h"
    #include "PN532.h"
    #include "NfcAdapter.h"

    PN532_SPI interface(SPI, 10); // create a PN532 SPI interface with the SPI CS terminal located at digital pin 10
    NfcAdapter nfc = NfcAdapter(interface); // create an NFC adapter object

    void setup() {
        Serial.begin(9600); // begin serial communication
        Serial.println("NDEF Reader");
        nfc.begin(); // begin NFC communication
    }

    void loop() {

        Serial.println("\nScan an NFC tag\n");
        if (nfc.tagPresent()) // Do an NFC scan to see if an NFC tag is present
        {
            NfcTag tag = nfc.read(); // read the NFC tag into an object, nfc.read() returns an NfcTag object.
            tag.print(); // prints the NFC tags type, UID, and NDEF message (if available)
        }
        delay(2000); // wait half a second (500ms) before scanning again (you may increment or decrement the wait time)
    }

Edit: Added code

What do you use for GSM / NFC - I2C mixed with SPI? Can you post the code?

I've had a quick google of I2C and SPI but don't fully understand them, to be honest with you, I have code reading a pressure sensor and reading an ultrasonic sensor then a separate sketch I intend to integrate into the first reading NFC tags. Apologies for the rubbish reply I'm very basic.

I have the Uno plugged into my mac via the serial port, then the NFC shield on top of that and the WiFi shield on top of that with the pins from the breadboard in it.

If you use I2C for NFC your nfc initialization will reflect that. I2C is IIRC a bus where each device is addressable 0, 1, 2, ... - haven't used SPI much. One thing about I2C I know is that one must keep the wires fairly short... <1m. Can you not share at least the init bits of your code?

Added the code, thanks. BTW all wires are extremely short < 10cm

That's SPI for the NFC. I don't know what the GSM uses. Try to use both with I2C. I used my PN532 in SPI mode, but switched to I2C to achieve less wire clutter. Is there a hardware conflict? I guesstimate you have something trying to use the same resource.

Why on earth are you calling loop() from startUp()?

Do you have "wires" plugged in to your breadboard "sensors" that connect to the same pins as the NFC shield? That is, D9-D13?

@Majenko I know that is poor practice, I did it while following what my code did during a debugging and haven't tidied it up since. In answer to your questions I have pins in D10, D11, D12 and D13.

You have a resource conflict between your breadboard sensors and the NFC shield.
int buttonPin = 13;    <= This is SCK
int trigPin = 11;      <= This is MOSI
int echoPin = 12;      <= This is MISO
int buzzerPin = 10;    <= This is chip select

You will have to use different pins for your sensors.

Majenko is in fact a cybernetic supercomputer comprised of a thousand chimpanzee brains, and several billion atmega368p's running on solar power in Area 51.

@user400344 Actually that's not entirely true any more. I replaced the several billion ATMega's with a single PIC32MZ. Next year I hope to start a big upgrade programme gradually replacing the chimpanzee brains with orangutan brains.

It is comforting that you're not a rasperry pi.

@user400344 I live in fear of being replaced by a small perl script...

Haha, perlNet will rule the earth and outlast humanity


text:
RFM69HCW 915 MHz radio module: Sending a stream of int values rather than char[ ]
I'm trying to send a stream of int values (0-4096) from one arduino to another using an RFM69HCW module.
Here's my main code:
#include <RFM69.h>
#include <SPI.h>
#define NETWORKID     0   // Must be the same for all nodes
#define MYNODEID      1   // My node ID
#define TONODEID      2   // Destination node ID
#define FREQUENCY     RF69_915MHZ
#define ENCRYPT       true // Set to "true" to use encryption
#define ENCRYPTKEY    "TOPSECRETPASSWRD" // Use the same 16-byte key on all nodes
#define RFM69_CS      10
#define RFM69_IRQ     2
#define RFM69_IRQN    0  // Pin 2 is IRQ 0!
#define RFM69_RST     9
#define IS_RFM69HCW   true
#define USEACK        true // Request ACKs or not
#define LED           9 // LED positive pin
#define GND           8 // LED ground pin
#define PULSEPIN      0 // Heart Rate Monitor at pin A0

RFM69 radio = RFM69(RFM69_CS, RFM69_IRQ, IS_RFM69HCW, RFM69_IRQN);
String pulsearray;
bool recHR = true;
unsigned long oldtime = 0;
int interval = 5000;
static int readtime = 3000;
static int sampletime = 10; // 1000/this is the thing
static int txinterval = 1000; // delay between transmissions

void setup() {
  initSerial();
  initLed();
  initRadio();
}

void loop() {
  unsigned long newtime = millis();
  if (!recHR && newtime - oldtime >= interval) {
    recHR = true;
    oldtime = newtime;
    Serial.println("recording HR now");
  }

  while (recHR) {
    unsigned long newtime = millis();
    if (newtime - oldtime >= sampletime) {
      readhr();
    }
    if (newtime - oldtime >= readtime) {
      recHR = false;
      oldtime = newtime;
      Serial.println("stopped reading HR");
    }
  }
}

And the function I'm using:
void readhr() {
  for (int i = 0; i < 20; i++) {
    int pulse = analogRead(PULSEPIN);
    pulsearray = pulsearray + pulse;
    pulsearray = pulsearray + '\n';
    Serial.println(pulse);
  }
}

The library function sendWithRetry() requires the following arguments:
bool RFM69::sendWithRetry(uint8_t toAddress, const void* buffer, uint8_t bufferSize, uint8_t retries, uint8_t retryWaitTime)

I would like a way to set up a buffer which can be transmitted in multiple packets during the 5 second analogRead() downtime.
Using a string as my buffer doesn't work when I try to transmit the first n (<60) characters in the String. I've also tried using a char[ ] as my buffer (a lot more troublesome when storing int values) but it still gives the same error:
exit status 1
no matching function for call to 'RFM69::sendWithRetry(int, String&, unsigned int)'

Do you have a specific question?

@sa_leinad my apologies, I should've been clearer.
I've edited my post to reflect my question.

You need to send the address of a buffer and the size, in bytes, of that buffer. What that buffer consists of is neither here nor there.
If you have an array of 10 ints you have a 20 byte buffer (since one int is 2 bytes on an 8-bit Arduino).
So you just pass it the address of the buffer (which as an array it is already just an address) and the size of that buffer:
int values[10];
// whatever to fill the array
RFM69::sendWithRetry(20, values, 20, 4, 1000);

As long as the array is statically created (e.g., a global variable with a fixed number of entries) you can use sizeof() to get the size in bytes:
RFM69::sendWithRetry(20, values, sizeof(values), 4, 1000);

As long as you receive at the other and using the same type of buffer it should be completely transparent.
To keep the system cross-platform and able to run on an Arduino that is either 8 or 32 bits and have them completely interoperable it is best to use variables with a fixed size. Instead of int use int16_t which is always 2 bytes and signed on every platform everywhere:
int16_t values[10];

Or use uint16_t if you want it unsigned.


text:
Software flashing attiny167 from RPi with avrdude
I am trying to flash a program onto an attiny167
(already bootloaded with the micronucleus bootloader)
with a Raspberry Pi via avrdude and USB.
Background
I have 50 Raspberry Pi 3B's connected to an amazon server collecting data.
I have 50 custom attiny167 based USB sensor PCBs which I will connect to the Pis
via USB (see this previous issue for more detail)
It is a struggle to access and connect each device (especially 50 of them),
and I thus need to be able to reflash a program to them via the commandline of an RPi.
I have bootloaded them all from my windows 10 machine and can flash any program via USB.
RPis
I have flashed programs from the RPi with an Arduino Uno, both with the IDE and avrdude.
 Arduino and avrdude are installed and working (installed both with apt-get).
The RPi can run an already flashed program, with reading and writing
 possible from the USB device.
 When plugged in the device is viewed by the lsusb command for 5 seconds.
 The pre-flashed program then runs and lsusb shows no device:
lsusb immediately after device is plugged into port

 pi@raspberrypi:/usr/bin $ lsusb
 Bus 001 Device 005: ID 046d:c077 Logitech, Inc.
 Bus 001 Device 006: ID 413c:2011 Dell Computer Corp. Multimedia Pro Keyboard
 Bus 001 Device 004: ID 413c:1005 Dell Computer Corp. Multimedia Pro Keyboard Hub
 Bus 001 Device 007: ID 16d0:0753 MCS Digistump DigiSpark
 Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. SMSC9512/9514 Fast Ethernet Adapter
 Bus 001 Device 002: ID 0424:9514 Standard Microsystems Corp.
 Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

lsusb ~5 seconds after device is plugged into port

 pi@raspberrypi:/usr/bin $ lsusb
 Bus 001 Device 005: ID 046d:c077 Logitech, Inc.
 Bus 001 Device 006: ID 413c:2011 Dell Computer Corp. Multimedia Pro Keyboard
 Bus 001 Device 004: ID 413c:1005 Dell Computer Corp. Multimedia Pro Keyboard Hub
 Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. SMSC9512/9514 Fast Ethernet Adapter
 Bus 001 Device 002: ID 0424:9514 Standard Microsystems Corp.
 Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

udev rules
I have followed the
tutorial for udev rules by digistump
and placed the file at /etc/udev/rules.d/49-micronucleus.rules
UDEV of tinseey (similar to bootloaded micronucleus for attiny167)
AVR Device
this post
hints it may not be possible,
however this issue may have been resolved, as I am using an attiny167 (rather than an 85),
and the Pi does not reboot on the USB being plugged in.
On using dmesg you can see it is unable to enumerate.
dmesg

[ 9820.701327] usb 1-1.2: new low-speed USB device number 7 using dwc_otg
[ 9820.803813] usb 1-1.2: New USB device found, idVendor=16d0, idProduct=0753
[ 9820.803838] usb 1-1.2: New USB device strings: Mfr=0, Product=0, SerialNumber=0
[ 9825.208851] usb 1-1.2: USB disconnect, device number 7
[ 9828.001334] usb 1-1.2: new low-speed USB device number 8 using dwc_otg
[ 9833.081359] usb 1-1.2: device descriptor read/64, error -110
[ 9833.271389] usb 1-1.2: device descriptor read/64, error -71
[ 9833.461352] usb 1-1.2: new low-speed USB device number 9 using dwc_otg
[ 9833.541349] usb 1-1.2: device descriptor read/64, error -71
[ 9833.731352] usb 1-1.2: device descriptor read/64, error -71
[ 9833.921349] usb 1-1.2: new low-speed USB device number 10 using dwc_otg
[ 9834.341388] usb 1-1.2: device not accepting address 10, error -71
[ 9834.421361] usb 1-1.2: new low-speed USB device number 11 using dwc_otg
[ 9834.841371] usb 1-1.2: device not accepting address 11, error -71
[ 9834.841480] usb 1-1-port2: unable to enumerate USB device

avrdude
I'm using the command, with different serial ports

usr/bin/avrdude -p attiny167 -c arduino -C /etc/avrdude.conf -b 19200 -P [COM PORT] -U flash:w:[MyHexFile.ino.hex]:i

this gives the error

avrdude: ser_open(): can't open device "[COM PORT]": No such file or directory

avrdude done.  Thank you.

The same method works with the Uno on the Pi, and the AVR device on my windows 10 machines.
I have updated the configuration file avrdude.conf to include the attiny167,
as I did with my windows 10 machine.
Serial port
serial and ttyACMO appears with Uno in /dev, not for the AVR device.
Arduino IDE
I've attempted to do this through the IDE but get the error:

/home/pi/Downloads/arduino-1.8.1/arduino-builder -dump-prefs -logger=machine -hardware /home/pi/Downloads/arduino-1.8.1/hardware -hardware /home/pi/.arduino15/packages -tools /home/pi/Downloads/arduino-1.8.1/tools-builder -tools /home/pi/Downloads/arduino-1.8.1/hardware/tools/avr -tools /home/pi/.arduino15/packages -built-in-libraries /home/pi/Downloads/arduino-1.8.1/libraries -libraries /home/pi/Arduino/libraries -fqbn=digistump:avr:digispark-tiny -ide-version=10801 -build-path /tmp/arduino_build_279218 -warnings=none -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.micronucleus.path=/home/pi/.arduino15/packages/digistump/tools/micronucleus/2.0a4 -prefs=runtime.tools.avr-gcc.path=/home/pi/.arduino15/packages/arduino/tools/avr-gcc/4.8.1-arduino5 -verbose /home/pi/sensicorn/sensicorn/indoorSoftware/Arduino Code/neopixel_simple/neopixel_simple.ino
/home/pi/Downloads/arduino-1.8.1/arduino-builder -compile -logger=machine -hardware /home/pi/Downloads/arduino-1.8.1/hardware -hardware /home/pi/.arduino15/packages -tools /home/pi/Downloads/arduino-1.8.1/tools-builder -tools /home/pi/Downloads/arduino-1.8.1/hardware/tools/avr -tools /home/pi/.arduino15/packages -built-in-libraries /home/pi/Downloads/arduino-1.8.1/libraries -libraries /home/pi/Arduino/libraries -fqbn=digistump:avr:digispark-tiny -ide-version=10801 -build-path /tmp/arduino_build_279218 -warnings=none -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.micronucleus.path=/home/pi/.arduino15/packages/digistump/tools/micronucleus/2.0a4 -prefs=runtime.tools.avr-gcc.path=/home/pi/.arduino15/packages/arduino/tools/avr-gcc/4.8.1-arduino5 -verbose /home/pi/sensicorn/sensicorn/indoorSoftware/Arduino Code/neopixel_simple/neopixel_simple.ino
Using board 'digispark-tiny' from platform in folder: /home/pi/.arduino15/packages/digistump/hardware/avr/1.6.7
Using core 'tiny' from platform in folder: /home/pi/.arduino15/packages/digistump/hardware/avr/1.6.7
Detecting libraries used...
"/home/pi/.arduino15/packages/arduino/tools/avr-gcc/4.8.1-arduino5/bin/avr-g++" -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections  -w -x c++ -E -CC -mmcu=attiny85 -DF_CPU=16500000L -DARDUINO=10801 -DARDUINO_AVR_DIGISPARK -DARDUINO_ARCH_AVR  "-I/home/pi/.arduino15/packages/digistump/hardware/avr/1.6.7/cores/tiny" "-I/home/pi/.arduino15/packages/digistump/hardware/avr/1.6.7/variants/digispark" "/tmp/arduino_build_279218/sketch/neopixel_simple.ino.cpp" -o "/dev/null"
Generating function prototypes...
"/home/pi/.arduino15/packages/arduino/tools/avr-gcc/4.8.1-arduino5/bin/avr-g++" -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections  -w -x c++ -E -CC -mmcu=attiny85 -DF_CPU=16500000L -DARDUINO=10801 -DARDUINO_AVR_DIGISPARK -DARDUINO_ARCH_AVR  "-I/home/pi/.arduino15/packages/digistump/hardware/avr/1.6.7/cores/tiny" "-I/home/pi/.arduino15/packages/digistump/hardware/avr/1.6.7/variants/digispark" "/tmp/arduino_build_279218/sketch/neopixel_simple.ino.cpp" -o "/tmp/arduino_build_279218/preproc/ctags_target_for_gcc_minus_e.cpp"

fork/exec /home/pi/.arduino15/packages/arduino/tools/avr-gcc/4.8.1-arduino5/bin/avr-g++: no such file or directory
Error compiling for board Digispark (Default - 16.5mhz).

when I type which avr-g++: /usr/bin/avr-g++, this is just a copy from my windows machine.
I found this github issue
and it seems to be irrelevant for now, just a path issue.
I've had to use a custom json file for the board manager to find micronucleus and Digispark Pro.
When I plug in the AVR device no new serial port is shown in Tools->Port (unlike Arduino UNO, ttyACM0 appears).
I'd much prefer to do flash via avrdude or similar on the commandline, so I have not focused on this.

My question
Is it possible to flash the AVR device with a Raspberry Pi over USB?
If so, what am I doing wrong?


text:
Ardunio Mega/ATmega2560: Using Port F or K for both analog inputs and digital outputs
On an ATmega2560, can ports have some pins used for analog inputs but others as digtial i/o? Specifically, I only need to use 3-5 analog inputs but have many digital inputs. I would like to use the remaining 3-5 pins as digital outputs if possible.
Additionally, does it make a difference if the port in question is Port F vs. Port K? For Port F, the datasheet seems to imply that all 8 of the pins are analog only if the ADC is enabled:

Port F serves as analog inputs to the A/D Converter.
Port F also serves as an 8-bit bi-directional I/O port, if the A/D Converter is not used.

For Port K, however, the datasheets port description does not have the distinction:

Port K serves as analog inputs to the A/D Converter.
Port K is a 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit).

It seems that this is definitely possible for the Arduino Uno/ATmega328P ADC port (except for the ADC6/7 pins for 32-pin form factors), but I can't seem to find anything confirming for the Arduino Mega/ATmega2560 or distinguishing between whether this is done on Port F or Port K

please provide a link to the datasheet that you are reading ..... also, which section in the datasheet are you referring to regarding port F?

Datasheet: https://ww1.microchip.com/downloads/en/devicedoc/atmel-2549-8-bit-avr-microcontroller-atmega640-1280-1281-2560-2561_datasheet.pdf
I was looking at section 2.3.8

On an ATmega2560, can ports have some pins used for analog inputs but others as digtial i/o?

Yes, the ADC MUX controls the selection of the pin that is connected to the converter. This is independent of the digital pin control.
Cheers!
PS: See the Arduino core source code for further details on the ADC MUX control registers.

Are you afraid to say that the datasheet is wrong? The part "if the A/D Converter is not used" for port F should not be there.

@Jot The ports (F and K) are digital but may also be selected to the ADC via the MUX and sample-and-hold. I guess that you interpret the datasheet as "to use port F for digital IO the ADC module must be turned off"? The is unfortunately wrong IMHO.

The digital input buffer (per pin) can be turned off when used for an analog input signal. The control register DIDRx controls this functionality. It is used to "reduce power consumption in the digital input buffer".

That is indeed how I read it. They can be used at the same time and the datasheet tells otherwise. Matthew had a good reason to ask this question. Even more so, because sometimes the digial pins are disconnected. For example for a atmega328p, when the x-tal is selected, the digital pins are disconnected for those x-tal pins. Beside the jtag, I think the description for the F and K port should be the same. @Matthew please mark the answer as a good answer.

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


text:
How to modify this code to simulate a binary encoder?
I have come across the following SPI slave code at this site:
#include <SPI.h>

char buf [100];
volatile byte pos;
volatile bool process_it;

void setup (void)
{
  Serial.begin (115200);   // debugging

  // turn on SPI in slave mode
  SPCR |= bit (SPE);

  // have to send on master in, *slave out*
  pinMode (MISO, OUTPUT);

  // get ready for an interrupt
  pos = 0;   // buffer empty
  process_it = false;

  // now turn on interrupts
  SPI.attachInterrupt();

}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
{
byte c = SPDR;  // grab byte from SPI Data Register

  // add to buffer if room
  if (pos < sizeof buf)
    {
    buf [pos++] = c;

    // example: newline means time to process buffer
    if (c == '\n')
      process_it = true;

    }  // end of room available
}  // end of interrupt routine SPI_STC_vect

// main loop - wait for flag set in interrupt routine
void loop (void)
{
  if (process_it)
    {
    buf [pos] = 0;
    Serial.println (buf);
    pos = 0;
    process_it = false;
    }  // end of flag set

}  // end of loop

How to modify the above code so that it responds to input clock signal just like in this SSI protocol? Uno or Nano can be used.

Basically I want to let an arduino  act as an absolute encoder so that it will transmit 13-bit binary data(it can be any random fixed binary data) as shown in the above SSI protocol. So the Arduino will output 13-bit binary data along with with start bit and tm taken into account as shown in the document above without parity.
The master's code I plan to use:
const int CLOCK_PIN = 2;
const int DATA_PIN = 3;
const int BIT_COUNT = 16;
void setup() {
    pinMode(DATA_PIN, INPUT);
    pinMode(CLOCK_PIN, OUTPUT);
    digitalWrite(CLOCK_PIN, HIGH);
    Serial.begin(115200);
  }
void loop() {
    float reading = readPosition();
    Serial.println(reading,2);
    delay(25);
  }

//read the current angular position
float readPosition() {
 unsigned long graysample = shiftIn(DATA_PIN, CLOCK_PIN, BIT_COUNT);
 delayMicroseconds(100); // Clock must be high for 20 microseconds before a new sample can be taken
unsigned long binarysample = grayToBinary32(graysample);
 return ((binarysample * 360UL) / 65536.0); // ouptut value from 0 to 360 with two point percision
}
//read in a byte of data from the digital input of the board.
unsigned long shiftIn(const int data_pin, const int clock_pin, const int bit_count) {
 unsigned long data = 0;
 for (int i=0; i<bit_count; i++) {
 data <<= 1; // shift all read data left one bit.

 //digitalWrite(clock_pin,LOW);
 PORTD &= ~(1 << 5); // clock pin goes low
 delayMicroseconds(1);
 //digitalWrite(clock_pin,HIGH);
 PORTD |= (1 << 5); // lock pin goes high
 delayMicroseconds(1);
 data |= digitalRead(data_pin); // cat the new read bit to the whole read data.
 }
 return data;
}
unsigned int grayToBinary32(unsigned int num)
{
 num = num ^ (num >> 16);
 num = num ^ (num >> 8);
 num = num ^ (num >> 4);
 num = num ^ (num >> 2);
 num = num ^ (num >> 1);
 return num;
}

What prevents you from doing this with digitalWrite() and delayMicroseconds()?

@EdgarBonet The SSI requires 100kHz minimum. Also Im not into the subject, I need this because I want to check a master library which can read incoming gray code from an encoder. But the encoder is too expensive so I wanted to mimic the slave

@EdgarBonet I would appreciate your answer but if dont have time or interest, I want to ask you if I do this with DigitalWrite() and delayMicroseconds(); I also need the slave to act with a clock as shown in SSI document. So it seems a bit more tricky than I was thinking.

That's a hard protocol to bitbang. You won't do it with SPI since it has things in there that SPI can't do. So forget SPI. You'd only do it with an interrupt for the clock and some very fast and tight code (which probably means assembly language).  Personally I'd implement it in a CPLD rather than an MCU.

@Majenko How about Arduino as master and using SPI?  I saw some using in some forums such as https://forum.arduino.cc/index.php?topic=156812.0 and  http://www.jgelectronics.nl/art-net-dmx/arduino-project-4.html I can at least buy a cheap encoder as slave but I need the master to work at least

You may try to bit-bang the protocol using direct port access. This
is less convenient, but way faster than digitalWrite(). Below is an
example, untested program. I am assuming the pinout is

data = PB0 = digital 8
clock = PB1 = digital 9
pins PB2 – PB5 (10 – 13) are unused

Edit: This updated program uses the clock as an input, and the data
as an output. The previous version used both lines as outputs, which was
due to a misunderstanding of mine.
#include <avr/io.h>

int main(void)
{
    uint16_t data = 0x155;

    DDRB  |= _BV(PB0);
    PORTB |= _BV(PB0);
    TCCR1B = _BV(CS10);  // start timer 1 @ F_CPU
    loop_until_bit_is_clear(PINB, PB1);

    for (;;) {
        loop_until_bit_is_set(PINB, PB1);
        PORTB = data & 1;
        data >>= 1;
        TCNT1 = -304;        // 20 us * 16 MHz - 16 cycles
        TIFR1 |= _BV(TOV1);  // clear overflow flag
        while (bit_is_set(PINB, PB1)) {
            if (bit_is_set(TIFR1, TOV1)) {  // timer overflowed
                PORTB = 1;  // data high
                data = 0x155;
                loop_until_bit_is_clear(PINB, PB1);
                break;
            }
        }
    }
}

This should be able to operate at frequencies up to about
200 – 250 kHz. There is a delay of about 0.5 µs
between the rising edges of the clock and the data been sent out, with a
jitter of 3 clock cycles.
The data word is sent least significant bit first, contrary to what the
protocol diagram shows. However, if you send arbitrary data, this should
not be an issue.
Note that this is a pure avr-libc program, which does not use the
Arduino core. It uses polling to check the inputs and the timer. The
interrupts are never enabled.

Thank you very much! I will try this with the master code I have. One arduino will be slave and the other will be master. Your code simulates the slave if Im not wrong but theres one thing Im a bit confused in your code. In this protocol slave supposed to receive clock signal. But in your code when I check digital 9 pin output by a scope, it outputs a very similar bit stream as digital 8. I thought slave would only receive clock signals as inputs from the master yet in your case the slave seems outputting bit stream. Am I getting something wrong here?

Re “In this protocol slave supposed to receive clock signal”: Oh, I see, I wasn't aware of this.

Please see that at the end of my question I now added the master code I found for a 16 bit encoder. The code is written for master and converts the gray code to binary. (Usually abs encoders output gray code for better efficenicny.) But for the slave side supposed the receive the clock in a way that each clock it outputs one bit.  More info about this protocol here: https://www.posital.com/media/posital_media/documents/AbsoluteEncoders_Context_Technology_SSI_AppNote.pdf My aim is to try this master code with a simulated slave. Slave can send any angle data. Better be constant data to check out

This works great! I just need to add in master code after return  //digitalWrite(clock_pin,LOW);
PORTD &= ~(1 << 5); // clock pin goes low
delayMicroseconds(1);
//digitalWrite(clock_pin,HIGH);
PORTD |= (1 << 5); // lock pin goes high
delayMicroseconds(1); to exactly mimic the required pattern. I checked it works great now thank you,

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


text:
Problem with transmitting 2 byte data in correct way
I'm using Atmel Studio with Atmega328P.
I'm trying to send the decimal number 876 continuously from the micro-controller. This was just to learn.
To send 876 I need two bytes which is:
0x036C = 00000011 01101100
So I manipulated a code and here is what I use now:
#include <avr/io.h>
#define F_CPU 16000000
#define USART_BAUDRATE 9600
#define UBRR_VALUE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)

void USART0Init(void)
{
    // Set baud rate
    UBRR0H = (uint8_t)(UBRR_VALUE>>8);
    UBRR0L = (uint8_t)UBRR_VALUE;
    // Set frame format to 8 data bits, no parity, 1 stop bit
    UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);
    //enable transmission and reception
    UCSR0B |= (1<<TXEN0);
}

int main (void)
{
    //Initialize USART0
    USART0Init();

    while(1)
    {

        UDR0 = 0b00000011;
        UDR0 = 0b01101100;

    }

}

The problem is at the receiving side the data comes as:
01101100
00000011
00000011
.
.
.
Here is the screen shot of the binary data at the receiving end:

However it should be received correctly as two byte chunks 00000011 01101100.
And here you can see the problem of the data being received as uint16(not only 876 as desired):

How can I fix this and receive the data properly as two bytes with correct order as 876?

you should wait until previous value was successfully transmitter and UDR0 is ready for next byte

The data sheet for the 328P - section 24.7.1 - contains an example of waiting for the transmission to complete before sending another byte.
When sending serial data, you determine the order of bytes and will need to reassembly in the correct order on receipt.  You can use bit shift operators to move the bytes back into the correct location.  If you send the most significant byte first (MSB) and then the least significant byte (LSB), putting them back into a 16 bit integer would look something like:
uint16_t result = (MSB << 8) | LSB;

i tried this works so far: UDR0 = 0b00000011; while(!(UCSR0A&(1<<UDRE0))){}; UDR0 = 0b01101100; while(!(UCSR0A&(1<<UDRE0))){};

Your code has a fundamental error: when you write "UDR0 = 0b00000011;", the CPU does not wait until the transmission is complete - that would be terribly wasteful, in terms of time. It just write to the transmit data buffer. Furthermore, if the transmission was not ongoing yet, that instruction also starts transmission (assuming the USART is properly initialized, as it is in your case). However, if a transmission is ongoing, and the data buffer is not empty, this write instruction might be either ignored or it might overwrite the data on the buffer.
Therefore, with your code, you're continuously writing two bytes (at a very high speed, because that loop would result in very few asm instructions), without checking if actually you can write to the transmit data buffer register. This will result in most of the bytes being "randomly" ignored, with some other being randomly picked and trasmitted.
Before sending any data, you must check if the data register is empty:
while ( !(UCSR0A & (1 << UDRE0)));
UDR0 = firstByte;
while ( !(UCSR0A & (1 << UDRE0)));
UDR0 = secondByte;

Where firstByte and secondByte are either the numeric values or two 8-bit variables.
Instead of the two "while" statements, you can use the built-in macro:
loop_until_bit_is_set(UCSR0A, UDRE0);

First, you want to determine what you are trying to send. Send data in binary form is rare.
Secondly, you want to wait for each transmission to send before starting the next one.

My goal is to learn to send 16bit unsigned data very fast way. I heard sending as bytes instead of strings is better for fast communication. What can I do for waiting between transmissions and how long? I dont know how to do that.

do you mean like this?:   UDR0 = 0b00000011;   while(!(UCSR0A&(1<<UDRE0))){};   UDR0 = 0b01101100;      while(!(UCSR0A&(1<<UDRE0))){};


text:
2 Arduino Unos Connected with 1-Wire and Receiver Pin getting Stuck High

I am trying to accomplish 1-wire communication between 2 Arduinos and so I wanted to start off by having 1 Arduino toggle a digital output pin and have the other read the state of that pin. To accomplish this, I have 2 computers with Arduino IDE installed and each one is connected to one Arduino Uno. Both Arduino Uno's are connected with a single male-male jumper cable on Pin 13 of the header. I am watching the state of the pin by looking at the prints in the Serial Console on both computers.
Here is a diagram of my setup:
Computer1 ---> Arduino1[Sender] --------> Arduino2[Receiver] -----> Computer2

The problem I have is that I am seeing when I first start both Arduinos - the sender is definitely toggling the output pin high->low->high forever - but the receiver Arduino only shows its input pin as toggling for a few seconds and then it gets stuck high. Sometime later, it may go low for 1 iteration, but then sticks at high again. What is going on? I would expect to see the sender and receiver show high->low->high forever. The code seems simple but I must be doing something wrong - thanks for your help.
Sender Code:
int led = 13; // Comm Pin

// Setup pins
void setup() {

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

  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);

}

void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  Serial.println("high");
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  Serial.println("low");
  delay(1000);               // wait for a second
}

Receiver Code:
int led = 13; // Comm Pin

// Setup pins
void setup() {

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

  // Pin is an input - normal state high
  pinMode(led, INPUT);

}
void loop() {

  // Put your main code here, to run repeatedly:
  Serial.println(digitalRead(led));
  delay(1000);

}

Do both Arduino share common GND? If not, your circuit just cannot work the way you want.

You should try to reduce the refresh time period on the receiver to 100ms and check if this still happens.

You should add a random delay in setup of receiver and reduce the sampling time of the receiver to 200ms.
That said, digital communication is an INSANELY EXTREMELY complex process, especially on the physical layer. This is not the correct way for two arduinos to digitally communicate.
Unless you are a teacher and are trying to demonstrate why this would fail, (not criticising), you mustn't use it.
You should use the Arduino wire library to establish communication instead. You can send whole integers, and it's totally reliable (it uses hash checks, guaranteeing correct communication even at 1152000 baud). As a comparison, you're at 1 baud.
You can get a tutorial here: http://www.instructables.com/id/I2C-between-Arduinos/.


text:
Decode VGA port by Arduino
Is it possible to read somehow VGA port of graphics card by Arduino? Even with some minimal 320 x 240 resolution and minimal frame rate per second, to convert pixels into numbers (for example) somehow. Who can show where to dig?

Your standard VGA (640x480@60Hz) has a 25.175MHz pixel clock. That's far too high for an Arduino to read as an analog signal. It's even to high to read as a digital signal through a comparator (1-bit monochrome). Added to that you have three signals, red, green and blue, you would want to sample the signal at 75.525Msps if done sequentially, or 25.175Msps if done with three ADCs in parallel.
Now the Arduino has no hope of ever doing that. However there are methods that could be useful - methods that allowed a lowly little 8-bit computer, such as the ZX Spectrum, etc, to capture graphics when running at only a couple of MHz (such as the Videoface).
One of the most interesting in this scenario is called progressive scan (not to be confused with the "progressive scan" used in HD terminology to mean the opposite of interlaced). With this you don't try and capture an entire frame in one go. Instead you capture just a few pixels from each scan line (and even only from a selection of scan lines) from each frame. In subsequent frames you capture a different selection of pixels. Over a number of frames (which can be quite a large number given the amount of data you'd need to capture) you will get the entire image. Of course this is no use if the image is rapidly changing since the image data that you would be reading would change part way through constructing your final image resulting in interesting banding effects.
About half way through this video you can see the scanning in action and how motion causes banding.
So yes, technically it is possible to capture VGA on an Arduino (maybe with the addition of extra external memory) however it is very hard to do it and the results may not be anywhere like what you actually want.

actually i want to convert black and white video somehow to view it on led panel with 64x128 leds for example. I want to create something like this https://www.youtube.com/watch?v=abPNrJshMns

Calculation:
320 x 240 resolution (assuming 8 bits for 256 colors) is 76,800 bytes
Assuming a frame rate of 50, that is 50 * 76,800 = 3,840,000 bytes/s
The most Arduino's are 16 MHz so assuming quite some instructions are needed (for converting and doing something) I doubt you will get this frame rate.
Also, you cannot store a complete page, but this may not be necessary.


text:
I would like to add a RGB led strip to my arduino alarm system
I am new to programming and would be grateful for any helpful answer...Thank you
I used a ping sensor, a piezo buzzer and an RGB strip. I used the Schematic from Adafruit Learning System..
Here is my code:
#define trigPin 5
#define echoPin 6
#define RED_PIN    10
#define GREEN_PIN   11
#define BLUE_PIN  9
int Buzzer = 3;

void setup() {
    //set pinModes for RGB strip
    pinMode(RED_PIN,OUTPUT);
    pinMode(BLUE_PIN,OUTPUT);
    pinMode(GREEN_PIN,OUTPUT);

    pinMode(Buzzer, OUTPUT);

    //reset lights
    analogWrite(RED_PIN,0);
    analogWrite(BLUE_PIN,0);
    analogWrite(RED_PIN,0);

    delay(5000);
    Serial.begin (9600);
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    pinMode(Buzzer, OUTPUT);
}

void loop() {
    int duration, distance;
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(1000);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = (duration/2) / 29.1;
    if (distance >= 80 || distance <= 0){
        Serial.println("No object detected");
        digitalWrite(Buzzer, LOW);
    } else {
        Serial.println("Object Detected");
        tone(Buzzer, 1000); // play 400 Hz tone for 500 ms
        delay(500);
        tone(Buzzer, 10000); // play 800Hz tone for 500ms
        noTone(Buzzer);
    }
    delay(300);
}

I think you need to be more clear about what you want to do with your RGB lights.

@deltaray I would like the rgb led strip to flash when the sensor is triggered, I am a novice at programming..

How do you have the LED strip connected, and what sort is it? A circuit diagram would be useful.

Would pictures work or do you want schematic

It really matters what type of RGB lights they are. Specifications like brand of lights or the chip that is used on the light strip, whether they are analogue or digitally addressable, how many lights there are on the strip and how many wires the strip has an what the wires are labeled would be a good start.  For instance, Neopixels from Adafruit are one type of digitally addressable light strip that uses its own protocol. A 5050 chip represents an analogue strip in which all colors would be the same at the same time.

The Led that I am using is 5M 5050 RGB SMD 300 LED Non-waterproof Change Color 12V Light Strip 24Key Remote

Also I am using a 12 volt source on the Vin for the RGB leds

An interesting problem with the Arduino paradigm is that not only do you need basic programming knowledge but you also need basic electronics knowledge.
On the plus side, there are plenty of good tutorials where you can over look these issues if you follow the tutorials step by step.  That is, get exactly the same parts and wire them up exactly the same way.  Later, if you like, you can go over the tutorial, ask questions here and discover how and why what you did works.
In your diagram:
You are implying you are using ordinary Red, Green & Blue LEDs and are going to vary their brightness using the Arduino's Pulse Width Modulation feature.
Possible problems:
You are powering the LEDs from the 9 volt pin of the Arduino.  And the LED strip in the diagram is clearly marked 12 volts.  This may work.  But is out of specification.
Also, this setup makes the assumption you are powering your Arduino with a 9 volt wall power supply.  Are you?  You could also power the Arduino with 5 volts using only the USB cable.  There would then be no 9 volts available at the 9 volt pin.  (I would avoid plugging in both power sources at the same time.  I think the Arduino design has changed over time.)
You are using a strip of Red, Green & Blue LEDs.  Which implies more than 1 of these Red, Green & Blue LEDs.  There is an upper current limit on the outputs of the Arduino.  More LEDs means more current.  Too many LEDs will damage the Arduino.  I would stick to 1 LED until you research the amount of current 1 LED takes verses the upper current limit of an Arduino output pin.

If you are not sure which LED lights you want to use, take a look at this tutorial  and use these LED lights
No, I have no connection to this video or its author.


text:
How do I control multiple LEDs strips with Arduino
I want to decorate my house with LEDs strips on each step of my stairs.
I will buy LEDs strips with a 12V power supply.
I want that if I put my foot on the first step, the first LEDs strip turn on, and after every second, the next step turn on too until the last step.
After 10 seconds on, the step must turn off.
To detect my foot, I'm thinking of using that kind of component : PIR (motion) sensor (product 189 on adafruit website). It act like a push button.
My first thought was to create two circuit loops.
One to supply the LEDs strips with a transistor between each strip.
And the second to control the transistor, so the turn on/off signal.
Thanks to your advices, I decided to use an Arduino to do the control loop.
I found this (http://www.zem.fr/decouverte-du-composant-74hc595-8-bit-shift-register/):

It's two 8-bit shift register, I have 16 steps on my stairs.
With a simple bit of code, I successed in writing a Arduino code that push ten HIGH(1) bits from the right then sixteen LOW(0) bits. So I have what I want with the LEDs.
The question is : how to connect the 16 LEDs strips with my circuit (instead of the single led) ?
English is not my native language, I tried to do my best.

motion activated LED's are annoying.  I prefer to leave them on always.  Using Blue or Red for effects and mounted directly under handrail.  You can drive from 12 to 14.2V to adjust brightness and feed with hidden phone wire. Les DEL activées par mouvement sont ennuyeuses. Je préfère les laisser toujours. Utilisation de bleu ou rouge pour les effets et monté directement sous la main courante. Vous pouvez conduire de 12 à 14.2V pour ajuster la luminosité et l'alimentation avec le fil téléphonique caché

Theoretically, you've got enough I/O to not use a shift register? You could also use a "digital led strip" which have individually controllable LED's. But aside from that, your option seems good.

Assuming your LED strips are essentially "always on" when they have power, you could replace the single LEDs in your diagram with transistors that sit between the power supply and the strip. Then, when your Arduino pin goes high, the transistor turns on the LED strip.

Yes, it is my first throught too, but I don't know which transistor I have to use. And Should I put the transistor before or after the LED strip ?

Take a look at my answer to similar question so you can get an idea how to use the transistors to light the LED strip.


text:
DAC to play audio samples
I have a buffer which contains 16000 PCM samples of 8Khz 8-bit mono. I am trying to play it using 12 bit MCP4725 DAC. I have tried using micros() to control the write interval for the DAC. Here's my code:
uint8_t soundData[16000] = { 234,206,79,255,249,....,210,222 }; // 8Khz 8-bit mono
long previousMicros = 0; // Sorry for missing this out!!

void setup() {

Serial.begin(115200);
Wire.begin(D2, D1);
delay(100); // delay 100 ms
Serial.flush();
delay(1000);

}

void value_write(uint16_t temp){

  Wire.beginTransmission(0x62);
  Wire.write(64);
  Wire.write(temp >> 4);        // the 8 most significant bits...
  Wire.write((temp & 15) << 4); // the 4 least significant bits...
  Wire.endTransmission();

}

void loop() {

  unsigned long currentMicros = micros();

// 125 uS sampling for 8KHz signal
if(currentMicros - previousMicros > 125) {
  Serial.print("Index: ");
  Serial.println(indx);
  uint16_t temp = map(soundData[indx++], 0, 255, 0, 4095);

  value_write(temp);
}

}

The write should logically be completed within 2 seconds but takes way more time. Any help regarding successfully writing the PCM values to the DAC at 8000Hz is greatly appreciated.

This is going to be a very jittery way to do things.  Typically you'd use a timer interrupt, or even (if you can afford to shut everything else off) a calibrated busy wait.

Can you give me a short example of how can I do this using timer interrupt?

In your code, you never set or update previousMicros value.

sorry for missing that out. I have updated

You need to update previousMicros every time you start a new send task. If previousMicrosnever gets updated, then your loop runs at top speed, and not metered by the if(currentMicros - previousMicros > 125) comparison. Try adding previousMicros += 125; just before the Serial.print("Index: "); line. This will cause your code to trigger approximately every 125 uS.

There was no change. I can observe in the serial monitor, it is approximately displaying 1000 values per second.

Doing a lot of serial printing may be messing up your timing. Do things work better if you disable all the Serial.print(...) commands in loop?

I think I can hear sound only for 2 sec now after disabling all the Serial.print. Also notices a change in write rate no sooner I removed one. The sample is actually unknown to me (the original audio) so could not confirm but could hear the beap only for 2 seconds. When I will be working ahead in the project, i will test it using known voice audio. Anyway, thankyou so much.

If this answered your question, mark it as an accepted answer so the system doesn't keep promoting it as unanswered.

Is Wire.setClock() necessary to code? Or alone this micros can handle the job?

Wire.setClock() sets the speed of the I2C transmission. The default is 100kHz. I believe you can also set it to 400kHz. You only need to use it if you plan to write data at a different bus speed than the default.

Just last question, is it that alone Wire.setClock(8000UL) can do my job without micros()?

No, setting the I2C clock to 8kHz, when you have to transmit several bytes of data per 125 uS will not work. You will have only transmitted 1 or maybe 2 bits of data before you are scheduled to send your next 14-bit command, plus the start/stop packets, etc.

One sample takes 38 I2C clock cycles to write. That's:
1 START
7 Address
1 R/W
1 ACK
8 Byte
1 ACK
8 Byte
1 ACK
8 Byte
1 ACK
1 STOP

At the default 100kHz clock speed that's 100,000/38 = 2631.58 samples per second absolute maximum.
You can increase the clock speed to 400kHz, which would allow you 400,000 / 38 = 10526 samples per second absolute maximum.  That would just about be do-able.
I am unsure what the ESP8266 can support, but the DAC also supports "High Speed" mode - 3.4MHz I2C.  If the ESP8266 supports that you can then run at 3,400,000 / 38 = 89474 samples per second, which is better still.
There's also the matter of the map() function which is just nasty in this situation. You can just bit-shift.
So besides just removing the Serial commands (which will slow things down massively) you should also:

Change the I2C clock to at least 400kHz
Change map() to soundData[indx++] << 4
Consider using a timer to trigger the sending of the samples

But, with all that said. an I2C DAC is really not suited to audio playback. I2C is just too slow and clunky for audio. You'd be better off with an SPI DAC which can run much much faster than I2C. Better still you should investigate I2S on the ESP8266. This is designed specifically for audio, although it's much harder to set up owing to the increased number of special clocks you need to provide ("master" clock, "bit" clock and "l/r" clock). Also the DACs (also known as CODECs) tend to be at least 16 bit or even higher, and capable of proper audio sampling frequencies, like 44100ksps and above.

Thanks @Majenko , I actually don't have to deal with a very high frequency as I am trying to play a voice sample recorded at 8KHz 8 bit mono and sound quality won't be an issue. Do I have to still go for I2S or I2C DAC would do the job for me.? And I would be going for 8000x38 = 304KHz for wire.setClock() but wish to do it using timers. It would be great if you can suggest me some reading

You want the clock frequency to be as fast as you can get. I2C specifications limit you to specific frequencies though - you can't just use any arbitrary value.