text:
Compiles but doesn't print anything
Here is my code. It is suppose to read a couple of sensors and print them out in the serial monitor. Any help please? Note that I'm new to object orientated programming.
/* The Blue Box

   Project description:
   Arduino black box flight data recorder
   This projects acts like a little homemade black box. It records data of a flying object.

   Details about the code:
   Altitude is calculated in meters above sea level.
   Records: day of the week, year, month, day, hour, minute, second, time from activation, yaw, pitch, roll, altitude, temperature

   This code is subject to a lot of ameliorations.

   By: xxx
   Date: 2016/08/28

   Extra credits:

   GY-521 library:
   I2Cdev device library code is placed under the MIT license
   Copyright (c) 2012 Jeff Rowberg
   https://github.com/jrowberg/i2cdevlib

   MPL3115A2 library
   Adafruit Industries
   https://github.com/adafruit/Adafruit_MPL3115A2_Library

   SD card library
   Code from example by Tom Igoe
   Included in the Arduino IDE itself

   DS3231 library
   Rinky-Dink Electronics
   http://www.rinkydinkelectronics.com/library.php?id=73
*/

#include <SPI.h>                        //include the SPI library
#include <SD.h>                         //include the SD card library
#include <Wire.h>                       //include I2C library
#include "I2Cdev.h"                     //include another I2C library
#include "Wire.h"                       //include another I2C library (yes, again)
#include "MPU6050_6Axis_MotionApps20.h" //include the MPU6050 library
#include "SparkFunMPL3115A2.h"          //include the MPL3115A2 library
#include <DS3231.h>                     //include the DS3231 library

//==================================================

#define testtest                    //*** COMMENT THIS LINE BEFORE UPLOADING OFFICIAL CODE TO FINAL PROJECT ***

#define chipSelect 10               //pin for the CS/SS
#define led 2                       //led and/or buzzer

volatile bool mpuInterrupt = false; //some random bool

bool ledState = false;              //state of the led and/or buzzer
bool dmpReady = false;              //state of the mpu6050

int yprInt[3];                      //gyro data in a integer because the extra precision of the float is total bullshit
int altitude;                       //altitude above takeoff point in meters
int altitudeCalibration;            //calibration for the altimeter
int temperature;                    //temperature in degrees Celcius

float counter = 0;                  //time counter, a somewhat internal clock that starts when the module starts dataloging

uint8_t mpuIntStatus;               //holds actual interrupt status byte from MPU
uint8_t devStatus;                  //return status after each device operation
uint8_t fifoBuffer[64];             //FIFO storage buffer

uint16_t packetSize;                //expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;                 //count of all bytes currently in FIFO

String day;                         //day of the week
String ymd;                         //date: year,month,day
String hms;                         //time: hour,minute,second

MPU6050 mpu;                        //change mpu's adress
Quaternion q;                       //quaternion container
VectorFloat gravity;                //gravity vector

MPL3115A2 myPressure;               //MPL3115A2 object declaration as myPressure
DS3231  rtc(A0, A1);                //DS3231 object declaration as

void dmpDataReady() {
  mpuInterrupt = true;
}

class MainLoop
{

    unsigned long previousMillis;

  public:
    MainLoop()
    {
      rtc.begin();            //start DS3231

      Wire.begin();
      myPressure.begin();                                         //start MPL3115A2 communication
      myPressure.setModeAltimeter();
      myPressure.setOversampleRate(7);
      myPressure.enableEventFlags();
      altitudeCalibration = myPressure.readAltitude();            //read altitude

#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE

      TWBR = 24;
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE

      Fastwire::setup(400, true);
#endif

      mpu.initialize();
      devStatus = mpu.dmpInitialize();
      mpu.setXGyroOffset(0);
      mpu.setYGyroOffset(0);
      mpu.setZGyroOffset(0);
      mpu.setZAccelOffset(0);

      if (devStatus == 0)
      {
        mpu.setDMPEnabled(true);
        attachInterrupt(0, dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();
        dmpReady = true;
        packetSize = mpu.dmpGetFIFOPacketSize();
      }

#ifdef testtest

      Serial.begin(115200); //start serial communication
#endif

#ifndef testtest

      if (SD.begin()); ();       //sd card
#endif

    }

    void go(  )
    {
      unsigned long currentMillis = millis();

#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE

      TWBR = 24;

#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE

      Fastwire::setup(400, true);
#endif

      mpu.initialize();
      devStatus = mpu.dmpInitialize();
      mpu.setXGyroOffset(0);
      mpu.setYGyroOffset(0);
      mpu.setZGyroOffset(0);
      mpu.setZAccelOffset(0);

      if (devStatus == 0)
      {
        mpu.setDMPEnabled(true);
        attachInterrupt(0, dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();
        dmpReady = true;
        packetSize = mpu.dmpGetFIFOPacketSize();
      }

      else
      {
        return;
      }

      altitude = myPressure.readAltitude() - altitudeCalibration; //read altitude
      temperature = myPressure.readTemp();                        //read temperature

      day = rtc.getDOWStr();  //get day of the week
      ymd = rtc.getDateStr(); //get day, month, year
      hms = rtc.getTimeStr(); //get hour, minutes, seconds

#ifdef testtest

      Serial.print(day);
      Serial.print(" ");
      Serial.print(ymd);
      Serial.print(" -- ");
      Serial.print(hms);
      Serial.print(", ");
      Serial.print(counter);
      Serial.print(", ");
      Serial.print(yprInt[0]);
      Serial.print(", ");
      Serial.print(yprInt[1]);
      Serial.print(", ");
      Serial.print(yprInt[2]);
      Serial.print(", ");
      Serial.print(altitude);
      Serial.print(" ,");
      Serial.print(temperature);
      Serial.println();
#endif

#ifndef testtest

      if (altitude > 1) //if the device is higher then 1m, then we sstart recording everything
      {
        File dataFile = SD.open("datalog.txt", FILE_WRITE);

        if (dataFile)
        {
          dataFile.print(day);
          dataFile.print(" ");
          dataFile.print(ymd);
          dataFile.print(" -- ");
          dataFile.print(hms);
          dataFile.print(", ");
          dataFile.print(counter);
          dataFile.print(", ");
          dataFile.print(yprInt[0]);
          dataFile.print(", ");
          dataFile.print(yprInt[1]);
          dataFile.print(", ");
          dataFile.print(yprInt[2]);
          dataFile.print(", ");
          dataFile.print(altitude);
          dataFile.print(" ,");
          dataFile.print(temperature);
          dataFile.println();
          dataFile.close();
        }
      }
#endif

      counter = counter + 0.5;

    }
};

MainLoop main;

void setup() {
}

void loop()  {
  main.go();
}

Why are you using a class in the first place?

Save a bit of memory and trying to learn new things.

Move all that code out of the constructor and put it in a .begin() method to call from setup(). You are calling functions before the chip has been initialized and things are being undone.
It is only safe to use a constructor to initialize a few variables and the like. Simply because the call sequence is:

Constructors
System Init
Setup
Repeat forever:
-> Loop

System Init configures the timers, peripherals, IO pins, etc. Things which need to be done before the code in your constructor.

mind giving a small example. im really not familiar with class and constructors...

Just rename your constructor to void begin() and then call main.begin() in setup(). Incidentally, calling it main is not good since that could cripple the main() function. Call it myMain instead.

im really not familiar with class and constructors - when an instance of a class is created its constructor (if it has one) is called to do preliminary housework. The constructor is a function with the same name as the class (in your case: MainLoop). On the Arduino it is not useful or safe to do much in a constructor other than setting variables (eg. setting them to zero).

You might also want to learn about the Static Initialization Order Fiasco problem in C++. A good example is using Serial in your own statically initialized class constructor (as you attempted). Which comes first - the Serial or MainLoop constructor...? Who knows...?

mind giving a small example. I'm really not familiar with class and constructors

Here is an example of trying to do things in the constructor:
class foo
{
  public:
  foo () // constructor
    {
    Serial.begin (115200);
    Serial.println ("Hello, world.");
    }
}; // end of class foo

foo bar;  // make an instance of foo

void setup() { }
void loop() { }

On my setup that prints "Hel" and nothing else.

Now if we change things around it works:
class foo
{
  public:
  void begin ()
    {
    Serial.begin (115200);
    Serial.println ("Hello, world.");
    }
}; // end of class foo

foo bar;  // make an instance of foo

void setup()
  {
  bar.begin ();
  }

void loop() { }

Now we are doing things in the right order. "Under the hood" the main function provided by the IDE initializes the hardware (by calling init) and then calls setup. Now we can call the begin function in our class.

It would have worked if we created the class instance inside setup because that is after init is called, like this:
class foo
{
  public:
  foo () // constructor
    {
    Serial.begin (115200);
    Serial.println ("Hello, world.");
    }
}; // end of class foo

void setup()
  {
  foo bar;  // make an instance of foo
  }

void loop() { }

However now bar is not a global variable.

What is sometimes done is to make a function to return an instance of the class, which creates it the first time it is called, like this:
class foo
{
  public:
  foo () // constructor
    {
    Serial.println (F("Hello, world."));
    }
  void doSomething ()
    {
    Serial.println (F("Doing something"));
    }
}; // end of class foo

foo & getFoo ()
  {
  static foo myBar;  // make an instance of foo
  return myBar;
  }  // end of getFoo

void setup()
  {
  Serial.begin (115200);
  Serial.println (F("Program starting."));

  foo & bar = getFoo ();
  bar.doSomething ();
  }  // end of setup

void loop()
  {
  foo & bar = getFoo ();
  bar.doSomething ();
  delay (500);
  }  // end of loop

Now the function getFoo returns a reference to the instance of foo created as a static variable inside it. Thus, the first time it is called, the instance is created. Subsequent times just return the same instance.


text:
Returning an int array from a function
I have a function that needs to return 3 int values. I currently use an array declared in the global scope and I ask the function to write into them. Is there a way to make a function return an array?
Here is what I want to do:
int function()
{

int array[3];

array[0] = 19;  //these are just random numbers

array[1] = 7;

array[2] = 69;

return array[]; //is this possible??

}

It won't work, or at least not reliably: you could only return a pointer to memory that is no longer allocated (bad). You can return an array embedded into a struct. Since it's only 3 ints, it should be fine.

That actually anwsers my question. You should have put it as an anwser, I'll acept it.

I have a function that needs to return 3 int values.

In the interests of completeness I'll suggest another method. Let's assume that you really need 3 values and not 300.
void foo (int & a, int & b, int & c)
{
  a = 19;  //these are just random numbers
  b = 7;
  c = 69;
}

void setup() {
  Serial.begin (115200);
  int x, y, z;
  foo (x, y, z);
  Serial.println (x);
  Serial.println (y);
  Serial.println (z);
}

void loop() {
}

This conceivably will use less memory because the compiler may be able to optimize all 3 values into registers. In fact in that specific example, it has optimized away the entire function call:
000000be <setup>:
  public:
    inline HardwareSerial(
      volatile uint8_t *ubrrh, volatile uint8_t *ubrrl,
      volatile uint8_t *ucsra, volatile uint8_t *ucsrb,
      volatile uint8_t *ucsrc, volatile uint8_t *udr);
    void begin(unsigned long baud) { begin(baud, SERIAL_8N1); }
  be:   26 e0           ldi r18, 0x06   ; 6
  c0:   40 e0           ldi r20, 0x00   ; 0
  c2:   52 ec           ldi r21, 0xC2   ; 194
  c4:   61 e0           ldi r22, 0x01   ; 1
  c6:   70 e0           ldi r23, 0x00   ; 0
  c8:   82 e2           ldi r24, 0x22   ; 34
  ca:   91 e0           ldi r25, 0x01   ; 1
  cc:   0e 94 64 01     call    0x2c8   ; 0x2c8 <_ZN14HardwareSerial5beginEmh>
  d0:   4a e0           ldi r20, 0x0A   ; 10
  d2:   50 e0           ldi r21, 0x00   ; 0
  d4:   63 e1           ldi r22, 0x13   ; 19  <---------- x
  d6:   70 e0           ldi r23, 0x00   ; 0
  d8:   82 e2           ldi r24, 0x22   ; 34
  da:   91 e0           ldi r25, 0x01   ; 1
  dc:   0e 94 4d 03     call    0x69a   ; 0x69a <_ZN5Print7printlnEii>
  e0:   4a e0           ldi r20, 0x0A   ; 10
  e2:   50 e0           ldi r21, 0x00   ; 0
  e4:   67 e0           ldi r22, 0x07   ; 7   <---------- y
  e6:   70 e0           ldi r23, 0x00   ; 0
  e8:   82 e2           ldi r24, 0x22   ; 34
  ea:   91 e0           ldi r25, 0x01   ; 1
  ec:   0e 94 4d 03     call    0x69a   ; 0x69a <_ZN5Print7printlnEii>
  f0:   4a e0           ldi r20, 0x0A   ; 10
  f2:   50 e0           ldi r21, 0x00   ; 0
  f4:   65 e4           ldi r22, 0x45   ; 69  <---------- z
  f6:   70 e0           ldi r23, 0x00   ; 0
  f8:   82 e2           ldi r24, 0x22   ; 34
  fa:   91 e0           ldi r25, 0x01   ; 1
  fc:   0c 94 4d 03     jmp 0x69a   ; 0x69a <_ZN5Print7printlnEii>

00000100 <loop>:
 100:   08 95           ret

There are several ways to achieve what you want:
The way that does not work
Did you try to compile the code you gave in the question? Then you
probably noticed it does not compile. I tried and got: “error: expected
primary-expression before ‘]’ token”, meaning the compiler expected
return array[some_index];.
The way that almost works
Remove the brackets and just return array:
int *function()
{
    int array[3];
    array[0] = 19;
    array[1] = 7;
    array[2] = 69;
    return array;
}

This may work, or not, depending on the surrounding code, on how the
optimizer processes your program, and on how lucky you are when you test
it. It is called “undefined behaviour” and is something you should
always avoid.
Here is what happens: in C (and C++) you cannot return an array. The
identifier array “decays” to a pointer pointing at its first element.
Then return array is essentially equivalent to return &array[0]. The
problem is that, since the array is allocated in the function's stack
frame, it ceases to exist when the function returns, thus the caller
gets a pointer to an area of memory that is not allocated anymore.
Likely memory corruption ahead. The compiler warned me when I tried to
do that: “warning: address of local variable ‘array’ returned”. It's a
very serious warning that should never be ignored.
The simplest fix: make the array static
As suggested by Chris Stratton in a comment, you can make the array
static, so it will be allocated for the whole life of the program:
int *function()
{
    static int array[3];
    array[0] = 19;
    array[1] = 7;
    array[2] = 69;
    return array;
}

The only catch is that the function is now not reentrant, meaning that
every time you call it it will clobber the same array it returned on the
previous calls. Depending on your use case, this may not be an issue,
but it's something you need to be aware of.
Have the caller manage the allocation
A safer (reentrant) way is to have the caller provide the memory needed
for the array. This is a very common method in C, and is suggested both
by Harper Shelby's answer and Chris Stratton's comment:
int *function(int array[3])
{
    array[0] = 19;
    array[1] = 7;
    array[2] = 69;
    return array;
}

The caller can allocate in static memory, or in it's own stack frame, or
on the heap... but you do not care, the allocation is the caller's
problem now.
A couple of things to note here:

The prototype is equivalent to int *function(int *array): the
function receives only a pointer. Writing array[3] instead of
*array has the sole effect of documenting that the function
expects the pointer to point to somewhere with room for 3 values. You
could document that in a comment instead.
The function could return void, since the caller presumably knows
the address it is giving you. Returning that same address is just for
convenience, as it can help you chain calls like
another_function(function(array)).

Return the array in a struct
One may wonder: why can't we return an array in the first place. I do
not know for sure why the authors of the language made this choice, but
one possible explanation is that it is expensive to return a big array
by value, as it involves copying the whole of it. Now, if your array is
really only three ints, then that argument does not apply, and you may
reasonably want to really return the whole array by value. This can be
done by embedding it inside a struct:
// Struct definition.
struct Array3 {
    int array[3];
};

Array3 function()
{
    Array3 a;
    a.array[0] = 19;
    a.array[1] = 7;
    a.array[2] = 69;
    return a;
}

Which of those would use the less memory possible?

Making the array global and letting both functions (caller and called) assume the use of that array, only requres the space for the 3 ints (6 bytes) but they remain reserved for the purpose for the entire program run, whether they are in use or not.
The other option is for the caller to allocate the array memory in its own stack and pass the called function a pointer to it. That uses not only the three ints but possibly, memory for the pointer as well (unless the compiler chooses to pass the pointer in registers - but lets assume worst case - that it gets passed in stack memory). ...

...  Then there is the additional memory (two more bytes) for the pointer), but the pointer's memory is only reserved while the called function is running. The array itself is only reserved while the caller (and thus the called) function is active. When the caller returns to its caller, the array space becomes free. So which uses less memory? It depends on when you look!

There are 2 ways to do what you want in C. One relies on the function caller managing memory, the other on the "library" code managing the memory. If you go with the caller-managed memory, your function accepts a buffer and fills it. For "library" managed memory, you provide additional functions to allocate and release the buffer that the caller then calls
If you want to use C++ idioms, you can make a class (possibly static) that allocates the memory and provides access to the data.

If you are going to allocate memory in the function/method be sure to do it in a lasting way - something placed on the stack for example will not outlive the return of the function call - it might still be there, but only unreliably.  Personally I'd use either a static allocation, or the caller's stack, as lasting runtime allocation introduces failure modes and is going to require about as much space to track the allocation as the 6 bytes that 3 Arduino ints would actually consume.

Absolutely true - I didn't go in to all the details, just pointed out the basic strategies. In the Arduino environment, having tracked allocations (and in most cases, any dynamic allocations) is probably not the way to go, for the reasons you mention.

source: Stack Exchange

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

sort: votes


text:
How do I handle multiple interrupts and outputs simultaneously?
I'd like to make a musical harp that utilizes break beam sensors.
I'd really appreciate guidance on these two questions:

How should I go about listening for multiple beam breaks at the same time? I'd like the box to be able to play cords, so I'd need to listen for the break beams while simultaneously taking the action do to other previous break beams. Are there any links to similar projects for guidance on handling multiple inputs (possibly multiple interrupts) at the same time, as well is multiple outputs?
Where is a good place to start to understand how to output non-buzzer sound with an Arduino? I bought a Adafruit Wave Shield to do the trick, but I'd appreciate advice on using this, or possibly taking an easier route.

My major concern is the first question however, and it makes me think I may need a Pi possibly? But I've never worked with those, so I'd like to avoid it if possible.
Thanks!  :)

Why do you need to use interrupts? Will the MCU ever be doing anything other than waiting for beam breaks and playing notes?

You may be right, right off the bat, but it leads to another question that I don't have the knowledge to know quite yet.... after I sense the break beam and start a 'C note' for x seconds, will I be able to simultaneously  sense another break beam while the 'C note' is playing and superpose another 'D note'?

That depends on how you're handling notes.

Do you have an example where you send a command to run in the background of an arduino, while the void loop continues on it's way? I'll go look for example on the Google too.

You still haven't explained how you're playing notes.

How many individual notes do you want to support?

It doesn't appear that the shield can mix sounds so chords will need to be hardcoded in the SD card

Awesome note, I think I'll have to find a new audio device to support my project.

Most of the examples for that shield seem to suffer from what could be called delayitis. If you first convert the piano example to a more state-based approach then the loop you want becomes much simpler:
#define NUM_BEAMS 12
// a single octave

char filename[NUM_BEAMS+5]; //init the last 5 chars to ".wav\0"
int previousInputs; //flag variable where each bit is a single beam

void loop(){
    int inputs = readBeams();

    if(inputs != previousInputs){
      previousInputs = inputs;
      if (wave.isplaying) {// already playing something, so stop it!
        wave.stop(); // stop it
      }
      if(inputs == 0){
        return;
      }
      for(int i = 0; i< NUM_BEAMS; i++){
          filename[i] = inputs &(1<<i)?'1':'0';
      }

      if (!f.open(root, filename)) {
        putstring("Couldn't open file "); Serial.print(name); return;
      }
      if (!wave.create(f)) {
        putstring_nl("Not a valid WAV"); return;
      }
      // ok time to play!
      wave.play();
    }

}

The SD card in the shield will need 4095 files, each containing the chord that must be played.
No need for interrupts, no messy interrupt based IO. Just a simple loop() where you read the input and if different from last time start playing a new file.
If you have a shield that can actually do sound mixing then, instead of needing a file for every possible chord, you can start playing the note when the corresponding bit in started = inputs & ~previousInputs; is 1 and stop playing the note when the corresponding bit in ended = ~inputs & previousInputs; is 1.

This is a great solution to avoid interrupts. I'm realizing that my shield isn't going to be able to do the trick cleanly, and that I'm going to need to find a shield that can do some level of mixing so individual sounds can come and go more naturally.

I quite like rachet freaks's idea, however whilst making an example for you his answer hadn't been posted. SO i'll chip in anyway!
In general it is possible to control and measure more than one input and output at the same time by the use of millis(). millis() is an arduino function that returns the number of milliseconds since the arduino fired up.
This probably doesnt sound overly useful to you straight away. But millis can be used in place of delay() if used correctly. Essentially you create a long variable to hold the beginning of an event and check the time since that event started with an if statement. If the difference in the current time and the start time is equal to the time you want the event to occur. Stop the event.
I appreciate my explanation might not be overly clear. So I wrote an example sketch. The sketch has two button inputs. And two button outputs. If one of the buttons is pressed one led will blink for 10 seconds, pressing the button mid blink will extend the time the led blinks by another 10 seconds. Whilst this is happening if you press the second button the other led will turn on, but only when the button is pressed. Using delay() to achieve this would not work nearly as well.
//Setup led and button pins
int ledPin1 = 3;
int ledPin2 = 4;
int butPin1 = 5;
int butPin2 = 6;

//Setup timers
unsigned long currentMillis = 0;
unsigned long blinkStartMillis = 0;
unsigned long ledOnMillis1 = 0;
unsigned long ledOffMillis1 =0;

//Setup variables to store input and output states.
int ledState1 = 0, ledState2 = 0; //State 1 for on, 0 for off;
int butState1 = 0, butState2 = 0; //State 1 for trigger, 0 for off;

//Setup trigger for event
int blinkTrigger = 0;

void setup() {
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(butPin1, INPUT);
  pinMode(butPin2, INPUT);

  delay(500);
}

void loop() {
    //Sets current millis for this loop
    currentMillis = millis();

    //Reads Button States
    butState1 = digitalRead(butPin1);
    butState2 = digitalRead(butPin2);

    //Setup to start blink if button 1 input is high
    if(butState1) {
      blinkTrigger = 1;
      blinkStartMillis = currentMillis;
    }

    //Handles Blinking
    if(blinkTrigger) {

      //If led1 off, and has been off for 500 milliseconds. led 1 on
      if(ledState1 == 0 && currentMillis - LedOffMillis >= 500) {
        digitalWrite(ledPin1, HIGH);
        ledState1 = 1;
        ledOnMillis = currentMillis;
      }

      //If led1 on, and has been on for 500 milliseconds. led 1 off
      if(ledState1 == 1 && currentMillis - LedOnMillis >= 500) {
        digitalWrite(ledPin1, LOW);
        ledState1 = 0;
        ledOffMillis = currentMillis;
      }

      //If led1 has been blinking for more than 10 seconds
      //Stop blinking
      if(currentMillis - blinkStartMillis > 10000) {
        digitalWrite(ledPin1, LOW);
        ledState1 = 0;
        blinkTrigger = 0;
      }
    }

    //While Button 2 pressed led 2 on
    if(butState2) digitalWrite(ledPin2, HIGH);
    if(!butState2) digitalWrite(ledPin2, LOW);

}

Note: The code style is a bit off because i rushed it, I would also usually use structs to hold the timers and event triggers.
Now for the Wave module rachet is bang on the money, you would need a file for every single note and every single chord.
I hope I helped, if not for your project maybe you may have learnt how to handle more than one event using event timings.

This is a great solution to the first problem. Thank you. I'm realizing that I'll hopefully be able to send the play command to the separate device, but my current choice for second device is questionable but functional.

How should I go about listening for multiple beam breaks at the same time?

use interrupts. it can be done with external interrupts, pin change interrupts, comparator interrupts, analog interrupts, or even timer interrupts, depending on how you intend to approach it.

I think I like this approach, but can an Arduino complete the interupt commands in the background while the void loop continues in the foreground? For example, I'd like to continue playing the 'C-note' while the arduino looks to see if a 'D-note' is played, and if so, I'd like to superpose these two 'notes', while looking to see if the 'C-note' was played again.

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


text:
Receiving i2c bytes on an attiny85
I've been trying to write a small i2c lib in C over the past week. I managed to get writing to slaves working (for example I can write to an ssd1306 oled) but reading (for example date/time from an ds3231) never works as my slaves don't seem to set SDA high when I request bytes.
uint8_t
i2c_read(uint8_t ack)
{
    uint8_t i, val;

    val = 0;
    cbi(SCL);
    DDRB &= ~(1 << SDA); /* Use SDA for input. */
    cbi(SDA); /* We need to pull down SDA to receive input. */

    /* Read 8bit from the slave. */
    _delay_us(DELAY);
    for (i = 0; i < 8; ++i) {
        sbi(SCL); /* Request one more bit. */
        _delay_us(DELAY); /* Wait a little so the slave can send his answer. */
        if (PORTB & (1 << SDA)) { /* Here the slave should have set SDA to 1 but it never does. */
            PORTB |= (1 << PB4);
            val = (val << 1) | 1;
        } else {
            val = (val << 1);
        }
        cbi(SCL);
        _delay_us(DELAY);
    }

    /* Send back an ACK or NAK. */
    DDRB |= 1 << SDA; /* Use SDA for writing. */
    if (ack)
        cbi(SDA); /* Set SDA to 0 to send ACK. */
    else
        sbi(SDA); /* Set SDA to 1 to send NAK. */

    sbi(SCL);
    _delay_us(DELAY);
    cbi(SCL);
    cbi(SDA);

    return val;
}

I set PB4 with to 1 when a slave actually sends a 1. Apparently that never happens.
I also had a look at how the various other libs out there do it but I didn't spot anything that would make a difference.
Any clues on what I migth be missing? Before reading my program sends the slave address to the bus. Also: please don't tell me to use other libraries since this is a learning project.

Hi and welcome to the Arduino.SE community. Thanks for your question.Please add more detail in your question on how this relates to Arduino. Cheers.

Does the clock line really get high? A slave can pull down the clock to pause the communciation until it is ready. Can you show us an output of an oscilloscope or a logic analyzer? So that we can see, what exactly happens on the lines?

Not sure, if this is the only problem, but you are reading from the wrong register.
There are 3 registers associated with a digital output pin: DDR, PORT and PIN. To read a pin, you need to read from the PIN register. Currently you are reading the PORT register, which will only ever have the value, that you set it to (zero in this case, because you cleared the bit beforehand with cbi(SDA);). When you configure the pin as input with the DDR register, the PORT register determines, if the internal pullup resistor is activated or not, so it cannot reflect the actual state of the pin. For this you need the PIN register.

Besides that, you might want to look into another thing, that might or might not be a problem in your case: I2C is an open drain bus, meaning, that it is driven actively low and passively high (through pullup resistors). I guess you already have external pullup resistors on your lines, so that you really can deactivate the internal pullup without breaking the communication. But imagine the following situation: The slave get's a request, but cannot clock it out that fast (for whatever reason). It can pull the clock to LOW, until it is ready to push out the data bit, slowing down the clock speed. (This can be done for every bit, unless you are in highspeed mode, then only before the start of a new byte). (This behavior is called clock stretching - Thanks to Edgar for the information) You don't monitor the line, so it can happen, that you drive the clock line actively to high, before the slave has released it. This results in a significant current between master and slave, since the master drives actively high and slave actively low.
There are implementations of I2C communication, that are just doing that and are working fine in most situations. I just wanted to give you this information. And if you at some point want to implement bus arbitration (to allow a multi-master setup), you definitely need this open drain behaviour.

Re. the slave pulling SCL low: I would add that this is called “clock stretching”, just to provide a search keyword.

You are correct, I totally forgot to mention it, though I thought I had done this. I will add this information to the answer

Thanks for the info! I didn't know that theres another register for reading input pins. But it makes sense since PORT is used for pullup/down in input mode. I have pull up resistors in my cirquit. They are integrated on the i2l slave ICs afaik. I am also waiting for the slave to stop pulling down SCL now (clock streching). Now I have the same problem but the slave does't pull down SDA (I guess) thus my SDA is always high (im reading from PINB). This is quite confusing. Have you got any ideas on what I might be doing wrong?

Edit: I have two i2c slaves that both have internal pull up resistort. Is it possible that they interfere in some way? I don't know a lot about electronics.

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


text:
NEMA17 and DRV8825 200 steps give only half revolution
I have this code:
#include <stdint.h>

# define STEP 14

void setup()
{
    pinMode(STEP, OUTPUT);
}

long steps = 0;
void loop()
{
    if (steps < 200)
    {
        digitalWrite(STEP, digitalRead(STEP) ^ 1);
        delay(10);
        steps++;
    }
}

Simple implementation and I have a nema17 motor with 1.8 degrees per step, which should give 200 steps per revolution, but I only have half a revolution on 200 steps, I tried connecting all MODEx pins to VCC and this should give me 6400 steps per revolution but 6400 steps also gives mi half an revolution.
Could there be an issue with the wiring of the motor? Why don't I receive a full revolution?
By full revolution I mean that the motor shaft should complete the whole circle but it completes only half.

See page 33 of the DRV8825 datasheet https://www.ti.com/lit/ds/symlink/drv8825.pdf.
DRV8255 moves the stepper on a rising edge in the signal.
That requires the signal to go low, then high.
That is two cycles of your program.
Add two lines to your code so that it is output low, delay 10, output high, delay 10

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


text:
Bootloader and AtmelStudio
I am having issues getting the main program to run after flashing via BOSSA with a bootloader. Jump to the bottom for my question and TL;DR.
Here is my current situation:

UF2 bootloader successfully compiled for SAMD21G18A
Bootloader flashed with ATMEL ICE and runs correctly upon reset
Device shows up as external storage and also as a CDC device in BOSSA
Flashed a hex file successfully in BOSSA (with offset applied) and then reset device
Program on hex file doesn't ever run

The program is just the Arduino "Blink" example, converted to an AtmelStudio solution. The linker script has been modified to have the origin at 0x2000 (as expected by the bootloader).
Other things I've tried to no avail:

a variety of offsets
many different bootloaders of CDC and MSD variants
uploading the compiled program with the Arduino IDE, BOSSA, AtmelStudio etc

Other points worth noting:

The AtmelStudio solution contains two projects as is standard when importing an Arduino sketch. 1) ArduinoCore 2) Blink
LEDs on my board work as expected (breathing to indicate in the bootloader)
When I import the Arduino sketch into AtmelStudio and flash it to the device the device mounts as a CDC device (via the native USB port) to my computer. I don't know why this is happening as the linker script doesn't include any provisions for a bootloader and the program itself doesn't instruct the hardware to enable the USB port. I have no idea why this is happening.
it seems like the bootloader never detects a program as it always runs upon startup. This is the behaviour when a program cannot be found.
The .hex file generated by the Arduino IDE doesn't ever launch either
If flashed from Arduino IDE or AtmelStudio directly the program does run

TL;DR:
Known working main program/sketch never gets run with bootloader on SAMD21G18A.
My question:
What would cause the bootloader to not find the main program and hence never run it?
Any other insights as to why I have not had any success here would be greatly appreciated too. My suspicions are that this has something to do with the way the main program is being compiled and linked.
Cheers!

and upload over the mass storage works?

the file transfer succeeds but the program never runs. The goal is to use CDC to upload though so I haven't put much energy into this


text:
Need Help to implement MODBUS TCP Master over Atmega32 MCU
I am doing a project where I have to interface with Fronius Solar Inverter with Atmega32 MCU over MODBUS TCP. I want to set the MCU as client and The inverter as Server and I have to implement two MODBUS Function only these are READ_HOLDING_REGISTER and WRITE_SIGLE_REGISTER and Function Code are 0x03 and 0x06 respectively.  I am newbie in this field and dont know about networking. Please anybody help me How can I develop the Software in C for this purpose??
The Document of Fronius Inverter for MODBUS TCP is Fronius MODBUS TCP Datamanger

Create A TCP connection (your inverter is TCP server) Check this, your device got modbus pattern so not modbus


text:
Arduino Uno lag in simple loop
I have a simple Arduino sketch which I have been playing with on my Uno.
The idea is simple, the user turns a potentiate (pin A2), when they pass a certain threshold a LED is turned on (pin 7).
Here is the code:
// Digital pins
const byte ledPin = 7;

// Analog pins
const byte userInputPotPin = A2;

// Potentiometer constants
const int userInputPotMinimumValue = 0;
const int userInputPotMaximumValue = 1023;
const int userInputMinimumValue = 1;
const int userInputMaximumValue = 100;

// Variables
const int threshold = 90;

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

    // Digital pins
    pinMode(ledPin, OUTPUT);

    // Analog pins
    pinMode(userInputPotPin, INPUT);
}

void loop()
{
    int rawValue = analogRead(userInputPotPin);
    int mappedValue = map(rawValue, userInputPotMinimumValue, userInputPotMaximumValue, userInputMinimumValue, userInputMaximumValue);

    String messageText;
    messageText += "Raw:   " + String(rawValue) + "\t";
    messageText += "Mapped:" + String(mappedValue);

    if(mappedValue > threshold)
    {
        messageText += "\tThreshold exceeded!";
        digitalWrite(ledPin, HIGH);
    }
    else
    {
        digitalWrite(ledPin, LOW);
    }

    Serial.println(messageText);

    delay(100);
}

The problem is that when it is run the hardware is very unresponsive - I can turn the pot, but I don't see the light change for several minutes. The log messages in the serial monitor also seem to be lagging behind.
I have tried:
* Removing the Serial statements (so there is no serial communication when the sketch is running), and just observing the LED. This makes no difference.
* Increasing the value in the delay up to 1000. This makes no difference in the responsiveness.
However, when I run the sketch on my Mega2560 the problem goes away and the circuit is as responsive as I expect.
Is there something wrong with my Uno board?

What happens when you also comment out all the code that uses and contructs the String messageText?

Your MCU is busy printing text and waiting.

I can't see anything in your code that could make it so slow. Could you try with just void loop(){Serial.println(analogRead(A2));delay(100);}?

It turns out the problem was the A2 pin on the board.
When I used the A0 pin (or a different board) the problem goes away.
I realised something was wrong when I noticed the values from the pot were strange (I expected values in the range 0 - 1023, but was receiving values from 170-250 ish).

Btw, you can use the Arduino 'map'  command to map a range to another range.

The String+ operator is very expensive. High likely what it does is:

Create a new block of memory to accommodate the old string content and the to-be-concatenated text.
Copy the current String to a new string location
Concatenate the string
Free the old memory

Besides creating memory gaps which can be disastrous for the just 2 KB SRAM of the Arduino Uno, it takes a lot of time.
Some tips:

Do not use Strings
Do not concatenate strings if not needed
To save more time, use short strings instead

If you really need to debug a time critical part, copy numbers you want to print to an array, and AFTER you do all 'real' code, start printing the numbers.

Also there is no reason to concat strings for serial output. Just print the parts one after another. To get "Number: 5 bananas" you could use Serial.print("Number: "); Serial.print(number_variable); Serial.println(" bananas")

@chrisl that's indeed my second tip.

Thanks for the excellent advice.
Unfortunately I can't mark it as the answer to the question as my issue was caused by something else (see my answer).

No problem, btw, you can accept your own answer too.


text:
Can you use digital pins as PWM output?
I am currently working on a robotics project that requires 16 PWM outputs to control 16 servos. Is it possible to use Arduino Uno's digital pins as PWM output pins through code?
If it is not possible, what microcontrollers do you suggest to use on such a project?

“The Servo library supports up to 12 motors on most Arduino boards and 48 on the Arduino Mega.”

You can get a PCA9685 servo controller card to multiplex 16 servos through I2C. e.g.:  https://www.adafruit.com/product/815

Only specific Digital Pins marked with ~PWM can generate a PWM signal. In the case of arduino Uno the pins 3,5,6,9,10,11 are all hardware PWM driven, and are marked on the Uno with a ~ or something.
Others can be driven with software PWM(though I wouldn't recommend it). As the Arduino Uno uses the ATMEGA328P, the number of pins is same with other boards using same processor.
On the other hand if you want to run 16pins for PWM, its best if you use Arduino MEGA 2560 because its processor supports more than 6 Hardware pins for PWM. Also you get the advantage of a higher memory storage for your code

PWM is not used to control servos.
Servos need a pulse that is 1 to 2 ms wide, with 1.5 ms wide being the center position, that occur every 20 ms (50 Hz).
A 2560 has enough timers and the library to control up to 48 servos.

It is a form of PWM, though not the PWM generated by analogWrite().


text:
HC-SR04 calibration conditions
As is known, the speed of sound depends of temperature and Relative Humidity. I'm trying to calibrate HC-SR04 sensor taking account these factors.
In SparkFun page there is no mention about environmental conditions in calibration (only is informed that speed of sound is 340 m/s). I found a paper with some calibration, but again it is no mention of original conditions.
I'm using the time elapsed per response to calculate distance in Arduino with access to a temperature & humidity chamber, so I want to recreate the calibration conditions to probe if the sensor is accurate.
Anyone know the environmental conditions of HC-SR04 calibration?

You are over thinking things. The difference is so small, and the accuracy of the HC-SR04 (especially when coupled with the Arduino) so poor that any "calibration" would be meaningless.

@Majenko Based in this research, difference between raw / temperature calibrated data is significant. My aim is to use it measuring water level in small reservoirs and pan evaporation for agriculture, so outdoor condition can affect significantly the output data and, consequently, farmer decision

How small? You are aware of the range limitation of those units?

@Majenko I'm thinking in a measuring range from 0.05-2.50 meters in a site from 0-35ºC (or even more) and 20-100% HR

The humidity might make like a 0.5% difference in the measurement.  At the range you're talking about I have my doubts that the Arduino would even be able to measure the difference in time.  Even if it could, you're talking about a difference of sub-millimeter proportions.  How accurate does the measurement really need to be?  I don't think the unit itself is that accurate on the timing to begin with.

@Delta_G could be. I will make different tests prior to check the effect of HR. But temperature has a measurable effect tested in fixed distance. At the moment, corrected data has a lower standard deviation

The HC-SR04 is not calibrated, nor does it take any measurements.
All it does is allow software on a connected microcontroller or system like an Arduino to measure the sum of the round trip time delay and some small internal offset delay, and from this calculate distance.
As the timing and calculation are entirely in your program, calibration is entirely up to you.
Under known conditions you could measure both a short and a long distance.  This would give you a slope and intercept - the slope from the speed of sound (which should not depend on the device at all, only on the conditions and your timing reference), and the intercept or offset, having to do with latencies in the system.
You could then cross-check at other distances, but under fixed conditions behavior should be linear.
As there is some initial ringing of the sender which can couple to the receiver and be mistaken for an echo, there will be a minimum distance below which you cannot reliably take a reading - as a guess, this is more than 5 cm, but you'll have to see, and it may even vary a little from unit to unit.
To a degree, it's a little bit amazing that these even work.  They use an RS232 level shifter to generate transmit pulses, and it's been alleged that the receive circuit is horribly mistuned, not really matching the emitted frequency at all... but despite that they do seem to work fairly well.


text:
Reading force from an FSR in Newtons
I hope I'm in the right place to ask, I couldn't find anything so I ask here, please tell me if I missed some relative topic.
I was following this tutorial : https://learn.adafruit.com/force-sensitive-resistor-fsr/using-an-fsr#in-depth-code-for-analog-fsr-measurements
and the only difference is that I have a potentiometer instead of a 900K resistor. I put it to 14350 Ohms because it fits the tutorial just above the last one, on top of the same page.
So here is the thing : I want to know the force in Newtons but the values I end up with are clearly wrong. A medium touch on the FSR is already > 3 Newtons, and it changes a lot when I turn the potentiometer to a higher resistance (and changing the value of that pota in the code too) : same force applied, different value of that force on the screen.
I know nothing about elecs so I would also like to know more about this part :
// Use the two FSR guide graphs to approximate the force
if (fsrConductance <= 1000) {
  fsrForce = fsrConductance / 80;
  Serial.print("Force in Newtons: ");
  Serial.println(fsrForce);
} else {
  fsrForce = fsrConductance - 1000;
  fsrForce /= 30;
  Serial.print("Force in Newtons: ");
  Serial.println(fsrForce);
}

Where does the /80 and -1000 then /30 come from ? Why is it a different operation and not just only different values ?
I'm using the same FSR but with 3.3V. I have the same graph as this one : https://learn.adafruit.com/force-sensitive-resistor-fsr/overview#how-to-measure-force-slash-pressure-with-an-fsr
I would really appreciate clear and simple explanations. Thank you by advance !

Looking at the graph and assuming fsrConductance == Resistance on the graph, then if you say that the fsrConductance is 7000, according to the above you should get 200 Newtons force, but the graph says 100 so there is something not right.  Is there something outside the sample of code that modifies fsrConductance?

I haven't changed fsrConductance, it's still fsrConductance == 1000000; like in the tutorial. It's in order to have our value in microOhms and conductance = 1 / resistance.

i do my projekt and i think i have the same Problem of you, i just want to ask you, did u get it the solve for Reading force from an FSR in Newtons ???? thanks

Sparkfun also sells FSR's and they explain it better: "Use them to sense if it’s being squeezed, but you may not want to use it as a scale".
On that Sparkfun page is also a datasheet. It's inaccuracy is 25%, and that is only when the force is applied evenly. When someone presses it with a finger, the inaccuracy is 50% or more.
The quick-and-dirty calculation in the Adafruit example is just for fun, it is not serious measuring the force in Newton.
There are two different calculations, for 'fsrConductance' above and below 1000. When it is above 1000, the 1000 offset is substracted to start the calculation at zero. The difference in calculation is that for one the value is divided by 80 and in the other divided by 30. It's just a rough calculation to get some kind of force value.
To measure weight or force, you need a load cell.

Hmmm I see now, thank you, that explains a lot ! It sounds so easy and obvious written like this.


text:
digispark - 2 pin push button to iterate through an hashmap
I'm trying to create a project with my digispark where i can iterate through an hashmap, when i press the push button the digispark writes via digikeyboard the values from an hashmap. Each time i press the button it's supposed to write the first value, then i press the push button again and in the same line it cleans what was written in the first value and writes the second value and so on. when the last value is reached it goes again to the first value if the button is pressed.
Right now i'm trying to put the iterator to work preperlly, this is the code i have:
#include "DigiKeyboard.h"
#include "HashMap.h"

HashMap<String, String> hashMap;
int i = 0;

void setup() {
   //setup hashmap
  hashMap.put("key0","test0");
  hashMap.put("key1","test1");
  hashMap.put("key2","test2");
  hashMap.put("key3","test3");
  hashMap.put("key4","test4");

  DigiKeyboard.sendKeyStroke(0);
  pinMode(0, INPUT);
}
void loop() {
  int sensorValue = digitalRead(0);
      while(sensorValue ==1 and i < hashMap.count())
      {
        delay(100);
        DigiKeyboard.println( hashMap.valueAt(i));
        i++;
      }
}

when i plug the digispark it prints automatically the first and the second value ("test0" "test1") and every time i press the button i get nothing.
This is my configuration:
http://cdn.instructables.com/FZA/0UN8/HI3TXV8D/FZA0UN8HI3TXV8D.LARGE.jpg
Can anyone help me please?

Have you read through your code yet?

hi there, yes, i've read it, and i know that the code don't do what i what to do but for now i just wanted to when i press the button the value from the first position appear, and when i push it again the next one appear in another line and so on...from there i would move for something more complex like cleaning the previous value and start from the beginning when the last value is reached...

You've looked at it, but you haven't actually read it. Read each line in loop() and understand fully what it does. Try explaining what each line does to someone else.

i've done that and the code inside the loop makes me sense: first loop: it reads the input from the pin 0, and enters the while, inside the while, while the sensorValue is equal to 1 (button pressed) and the i variable is less than the number of item inside the hashmap (5 items), in the first loop the i = 0 so 0 < 5 and it enters the while, inside the while it will print the value from the hashmap in the position 0 (test0), after this it will increment the i variable and start over again...

"sensorValue is equal to 1 (button pressed)" Those are two independent things. You have no idea what the state of the button is after the assignment.

thank you all.
i've manage to found a solution to my problem with this code, probably is not the most elegant way to do it but it works:
#include "DigiKeyboard.h"
#include "HashMap.h"

HashMap<char*, char*> hashMap;
int i = 0;
bool flag;

const byte switchPin = 0;
byte oldSwitchState = HIGH;  // assume switch open because of pull-up resistor
const unsigned long debounceTime = 100;  // milliseconds
unsigned long switchPressTime;  // when the switch last changed state

void setup ()
  {
  pinMode (switchPin, INPUT_PULLUP);

     //setup hashmap
  hashMap.put("key0","test0");
  hashMap.put("key1","test1");
  hashMap.put("key2","test2");
  hashMap.put("key3","test3");
  hashMap.put("key4","test4");

  DigiKeyboard.sendKeyStroke(0);

  }  // end of setup

void loop ()
  {
  // see if switch is open or closed
  byte switchState = digitalRead (switchPin);

  // has it changed since last time?
  if (switchState != oldSwitchState)
    {
    // debounce
    if (millis () - switchPressTime >= debounceTime)
       {
       switchPressTime = millis ();  // when we closed the switch
       oldSwitchState =  switchState;  // remember for next time
       if (switchState == HIGH)
          {
            delay(500);
            flag = true;
           while(i < hashMap.count() and flag == true)
            {
              DigiKeyboard.println( hashMap.valueAt(i));
              i++;
              flag = false;
              }
          }  // end if switchState is LOW
       }  // end if debounce time up

    }  // end of state change

  // other code here ...

  }  // end of loop

Even with a "clean" button, your while() loop will whip through all 5 hashmap values before you can release the button.
Switches and button aren't clean. They will (appear to) bounce, sending many pulses before they settle down to a fully on or fully off state. Read Nick Gammon's tutorial on de-bouncing switches.
I'm not familiar with your display but if it is a one-line display, and you .println() at it, will the newline character "scroll" the line of text off the display? This could explain why you didn't at least see the final line. You may need a plain .print() call in order not to do that.
Most LCD displays have a set of control codes to clear it, move the cursor, etc., which you would have to embed into the text string you send, or send using separate .print() calls. I don't see any provision in your code for including or sending those, so you'll need to fix that, too. Right now, I expect your display receives something like
test0\ntest1\ntest2\ntest3\ntest4\nIt probably needs to see something more like\033Etest0, e.g., for the first one, etc. That cruft at the beginning of the string is the VT52-code,escE, for "Clear the display". (I have no idea what command set your display uses, but the VT-52 commands have been in use for ... um, hmmph! well, a long time, anyway. :)  You'll probably to replace it with whatever your particular device uses.


text:
Relay controller with IO expander
found this
http://www.zevendevelopment.com/relayexpander.html
I was looking to control 48 relays in sequential order with external controls for duration and frequency. How do I properly communicate to the boards? Sorry new to this setup.

Looks like you communicate via the IOExpander board.

Their IO expander gets controlled via Serial (UART). From there all the relay expanders are controlled. Have you already bought these boards?

I guess what I’m really saying is I’m not clear on how to properly code this. I have not bought these boards yet but they seem like the perfect solution. Would you recommend anything else?


text:
Audio Zero not responding on MKR Zero
I have a Arduino MKR Zero set up with a sd card in it and a speaker hooked up to the ground and DAC0. I have a .wav file on it called "test.wav" and it is 8 bit mono 88200hz recording. I am using the AudioZero example to try to play this audio file off the speaker but it is not working. When I upload and run the code and open the Serial Monitor to check to see if it has any errors or sucesses reading the files it is just blank. It uploads the code all fine, but the Serial Monitor says nothing at all and the speaker doesnt play anything. Did I set it up wrong somehow?
Here is the code that it is running:
  Simple Audio Player for Arduino Zero

 Demonstrates the use of the Audio library for the Arduino Zero

 Hardware required :
 * Arduino shield with a SD card on CS4
 * A sound file named "test.wav" in the root directory of the SD card
 * An audio amplifier to connect to the DAC0 and ground
 * A speaker to connect to the audio amplifier

 Arturo Guadalupi <a.guadalupi@arduino.cc>
 Angelo Scialabba <a.scialabba@arduino.cc>
 Claudio Indellicati <c.indellicati@arduino.cc>

 This example code is in the public domain

 http://arduino.cc/en/Tutorial/SimpleAudioPlayerZero

*/

#include <SD.h>
#include <SPI.h>
#include <AudioZero.h>

void setup()
{
  // debug output at 115200 baud
  Serial.begin(115200);

  // setup SD-card
  Serial.print("Initializing SD card...");
  if (!SD.begin(SDCARD_SS_PIN)) {
    Serial.println(" failed!");
    return;
  }
  Serial.println(" done.");
  // hi-speed SPI transfers
  SPI.setClockDivider(4);

  // 88200 sample rate
  AudioZero.begin(2*44100);
}

void loop()
{
  int count = 0;

  // open wave file from sdcard
  File myFile = SD.open("test.wav");
  if (!myFile) {
    // if the file didn't open, print an error and stop
    Serial.println("error opening test.wav");
    while (true);
  }

  Serial.print("Playing");

  // until the file is not finished
  AudioZero.play(myFile);
  AudioZero.end();

  Serial.println("End of file. Thank you for listening!");
  while (true) ;
}

add while (!Serial); after Serial.begin to wait for Serial Monitor connection

When I do that it looks like it is initializing correctly because the serial monitor now says Initializing SD card... done.   But then it just freezes on that and doesn't get any further.

try the CardInfo example of the SD library

The card info example runs just fine and gives me all the info with no errors.

did you test the speaker or buzzer with tone()?

Yes I did. The tone works just fine as well.

To use the Serial monitor with Arduino MKRZERO, use SerialUSB instead of Serial, i.e. SerialUSB.println("something");


text:
Getting an Arduino Uno and MKR zero to communicate
I'm very new to Arduino and especially the forum so please let me know if I am on the wrong topic or anything.
Anyways let me get straight to the point. I am working on a school project where I need to create a robot head that can move and talk using the Arduino Uno. I have the speech files as a .wav and from what I gathered you need an sd card reader connected to the Uno to read .wav files. So I purchased the Arduino MKR Zero, but after I got the board I realized that it is a standalone board, not a file reader for the Uno. This project is due next week so I need to figure out how to make the MKR Zero read the files and play them off the speakers but have it timed and programmed off the Uno. Is this possible with the hardware I have?
Here is a picture of my setup:

you don't need the Uno

I do because the MKR Zero doesn't have enough ports for all the motors that I need to use for my project.

Let the MKR Zero play the wav files. It has DAC on A0 and AudioZero library to play wav files from SD card.
You can use Serial communication to command the Zero from Uno. In Uno use hardware Serial or create SoftwareSerial to send commands to Serial1 of MKR Zero. You can then test the MKR first with commands sent from Serial Monitor.


text:
Using arduino as a remote control
I have old Sony amplifier (F117R) and CD player (CDP-590), both equipped with IR remote controls. The problem is that I bought them as vintage without remotes.
I have a rough idea how to build dedicated RC for both units but I'm missing the essential part - how is the signal encoded for the units?
I can find tutorials where the can be taught the codes from working remote control and how to build universal RC from that.
Is there any chance where to find IR codes for Hi-Fi units remote controls?

Just a little suggestion on an alternative approach:
https://www.ebay.ie/itm/Original-Sony-RM-S310-Remote-Control-for-TA-F410R-F411R-Audio-System-Tested/264447792621
https://www.ebay.ie/itm/Remote-Control-For-Sony-CDP-590-CDP-391-CDP-M201-CDP-M301-Compact-CD-Player/274003755223

https://irq5.io/2012/07/27/infrared-remote-control-protocols-part-1/

http://hifi-remote.com/wiki/index.php?title=Main_Page

http://picprojects.org.uk/projects/sirc/sonysirc.pdf

http://www.righto.com/2010/03/understanding-sony-ir-remote-codes-lirc.html

IR remote controls are not simple enough to be properly addressed in much less than a book. You will find this article VERY useful. There are hundreds of codes that use this format and it is likely you will find what you need. http://www.remotecentral.com/features/irdisp1.htm


text:
Servos and Random Number
I am new to coding and this website so I apologize if I make any mistakes. I am trying to get servos to move when a random number is generated. Like if I roll a 2 I want servos 1, 2 and 3 to open and then if I roll a 3 after I want servos 4, 5 and 6 to open. I am able to hold the previous values in the code now but can't get the servos to go with it. Any help is great! Thanks!
#include <Servo.h>

Servo myservo;

int pos = 0;    // variable to store the servo     position
int x = 0;
int button = 8;
int BUTTON;
int randomNumber;
int xPrevious = 0;
int oldNumber;

void setup() {
pinMode(button, INPUT);
Serial.begin(9600);
}

void loop() {

BUTTON = digitalRead(button);
Serial.println(BUTTON);
 if(BUTTON == LOW){
  randomNumber = random(1,4);
  delay(275);
  Serial.print("Random Number ");
 Serial.println(randomNumber);
 if( xPrevious == 0) {
   randomNumber = randomNumber + 1;
 }

  // Only want it to do this on the first roll.
     xPrevious = randomNumber + xPrevious;
     Serial.print("xPrevious ");
     Serial.println(xPrevious);
    oldNumber = xPrevious;

 for (x = randomNumber; x <= xPrevious; x += 1) {
  myservo.attach(x);
  Serial.println(x);

  for (pos = 0; pos <= 180; pos += 1) { // goes     from 0 degrees to 180     degrees
 //in steps of 1 degree
    myservo.write(pos);              // tell servo to go   to position in variable 'pos'
    delay(15);                       // waits 15ms for the     servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes  from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go    to position in variable 'pos'
    delay(15);                       // waits 15ms for the  servo to reach the position
  }

 }
 }
 }

Can you explain more? I still don't get the "random" pattern

Yeah so it is basically going to be a game where you roll a random number and when you get that number servos will open. For example I roll a 2 on my first time so servo 1,2, and 3 will open. 1 will open because that is where a ball starts. Then on the next turn I roll a 5 so servos 4,5,6,7,8, and 9 open. Does that make more sense?

if "n" is a random number, the opened servo are servo(0+prevpos+1) through servo(n+prevpos+1)? correct?

I think that is it

You planning to use multiple servo, but only declare one.
I still don't get about the pattern, but maybe this will give some image:
Servo myservo[5]; // assuming you have 5-servo
                  // servo[0]--> pin 0
                  // servo[1]--> pin 1
                  // servo[2]--> pin 2
                  // servo[3]--> pin 3
                  // servo[4]--> pin 4
pos = 0;

void loop() {

BUTTON = digitalRead(button);
Serial.println(BUTTON);
 if(BUTTON == LOW){
  randomNumber = random(1,4);
  delay(275);
  pos+=randomNumber;
  Serial.print("Random Number ");
  Serial.println(randomNumber);
  Serial.print("Current pos ");
  Serial.println(pos);

 for (x = 0; x < randomNumber; x++) {
  myservo[x+pos].attach(x+pos);
  Serial.print("attach servo-");
  Serial.println(x+pos); }

//open (move from 0-180 degrees)
 for (x = 0; x < randomNumber; x++) {
  myservo[x+pos].write(180);
 }
 delay(2000);

//close (move from 180-0 degrees)
 for (x = 0; x < randomNumber; x++) {
  myservo[x+pos].write(0);
 }
 delay(2000);

//detach servo
 for (x = 0; x < randomNumber; x++) {
  myservo[x+pos].detach();
 }
 delay(2000);
}
}


text:
Understanding bitwise operations
I am wondering what the second line of code does:
int16_t GyX;
GyX=Wire.read()<<8|Wire.read();

Also, how can I write the GyX value to EEPROM?
From what I understand, int16_t is a two-bytes value. The Wire.read() returns a single byte. The <<8 shifts the bits by one byte to the left in order to read the higher order bits, and the last part writes the next wire read (lower order bits). Basically, reads wire twice and stores those values in the int. Is that correct?
For the writing, would
EEPROM.write(addr, GyX >> 8);
EEPROM.write(addr, GyX & 0xff);

do the trick? (First line records the higher order bits, while second records the lower order ones)

@PetioPetrov, Arduino has macros to make it easier: highByte, lowByte, and word.
You don't have to split and combine bytes and words. The EEPROM.put and EEPROM.get can write and read two bytes if you want to. It's all documented in the reference of EEPROM.
There is a lot going on in this piece of code:
int16_t GyX;
GyX=Wire.read()<<8|Wire.read();

Shifting a single byte 8 bits to the left would be wrong. However, the Wire.read returns an integer and the GyX is an integer. Therefor the compiler uses integers for everything and shifting 8 bits to the left is valid.
At this moment with the current Arduino and avr-gcc compiler version, it will call the Wire.read for the high byte first and then the Wire.read for the low byte. That is pure luck as @EdgarBonet has corrected me below. In the c++ language there is no specified order of calling functions.
The bitwise 'OR' with the '|' could be a problem when there was no data and -1 was returned by Wire.read.

“Even with the most extreme optimizations, the order is in this situation still from left to right”. No. The order is unspecified. See Order of evaluation in C++.

@EdgarBonet, Thanks for the correction. I thought that when a call was made to the same function, it would always work. But the C++ language explicitly has defined that there is no specified order. I will try to remember that.

GyX=Wire.read()<<8|Wire.read();

This is a bug. It reads two bytes from the I2C bus and builds a 16-bit
number from them. One of the bytes (we don't know which one) will be the
most significant byte of the result. The other byte will be the least
significant byte.
This instruction is likely to work just fine on some particular version
of some particular compiler with some particular compiler options.
Presumably it did work for the author. But you should not expect it to
work consistently across compilers, or even across different versions of
the same compiler.
The proper way to do this is to perform the two reads in different
instructions:
GyX = (uint16_t) Wire.read() << 8;
GyX |= Wire.read();

assuming the bytes come most-significant first.
Edit: added (uint16_t) cast. C.f. this answer.


text:
Problem with the Frequency meter code
I am trying to build a frequency meter using Interrupts and Timer1, which works as if the system receives an Interrupt it would get the timer's data and would calculate

Signal's Frequency = 1 / (Counter * Timer's Period) => F_s = F_t/TCNT

but the result is way off, and it does not even make sense. I have had altered my code to look that if the timer's data is not valid or sth, but the number that the timer counter has counted is sth that I expect.
Here is my code:
int f=0;
char msg[50];

void setup()
{
  Serial.begin(115200);
  noInterrupts();           // disable all interrupts
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
  TCCR1A = 0;
  TCCR1B = 0;
  OCR1A = 0;
  OCR1B = 0;
  TCCR1B |= (0<<CS12)|(1<<CS11)|(0<<CS10);    // Clock 2MHZ
  TCNT1  = 0;
  TIMSK1 = 0; // disable timer overflow interrupt
  interrupts();
  attachInterrupt(1,pin_ISR,RISING);
}

void pin_ISR(){
  //digitalWrite(13,!digitalRead(13));
  f = 2000000/TCNT1;
  TCNT1=0;
}

void loop()
{
  sprintf(msg,"Humidity:%d \n",f);
  Serial.print(msg);
}

Your code works for me but, as @Jot noted, it would be more robust if you make f volatile and read it with interrupts blocked.

As stated in my comment, your code is kind of fine. Id mostly works,
but it looses a few microseconds on each iteration. If you are looking
at multi-kHz frequencies, you probably want to avoid loosing
microseconds. The solution is simple: never reset the counter. I
changed you ISR as follows:
uint16_t previous_counter;

void pin_ISR(){
    uint16_t counter = TCNT1;
    f = 2000000/(counter - previous_counter);
    previous_counter = counter;
}

and now it gives the correct frequency... on average. There are some
variations though, dues mostly to delays caused by other interrupts.
Edit 1: If you want to avoid the fluctuations caused by other
interrupts, your best bet is probably to use the input capture feature
of Timer 1.
Edit 2: Here is why your measurement was somewhat off. Your original
ISR essentially does something like this:
void pin_ISR() {
    uint16_t temporary_value = TCNT1;
    loose_some_time();
    TCNT1 = 0;
}

The time you loose in the ISR is the part of the signal period you are
not measuring, which means you are underestimating the period by that
much. In the ISR you posted, this is mostly the time taken by a 32-bit
division, which is quite significant. A simple improvement would be to
clear TCNT1 right after reading it:
void pin_ISR() {
    uint16_t temporary_value = TCNT1;
    TCNT1 = 0;
    loose_some_time();
}

and now the average period you measure is almost right. It is not
perfect though, as the whole reading and writing of TCNT1 takes
8 CPU cycles.
The alternative I am suggesting, where you never clear the timer, is
the correct way of measuring a period with a timer interrupt: you don't
loose a single CPU cycle. The best way is to use input capture: you get
rid of the software-induced jitter.
Note: You should also take care of the very valid points raised in
Jot's answer, about making f volatile and reading it with interrupts
disabled.

This worked perfectly. Thanks! But I don't get it, my timer was ticking on a 2Mhz clock, and the number of TCNT is usually around 297, 298 if I change the code to display that, and with the way you told me to change it, it still remains very much the same. I don't know why this is happening! Although I must say that I am simulating my program in Proteus.maybe it's a bug.

Did you find an example that works that way ? Is it, for example, allowed that the TCNT1 is cleared in an interrupt routine? The TCCR1A is cleared, but not set to a value ?
[edit] Clearing TCCR1A is okay. Clearing TCNT1 is also okay, but can be improved as @EdgarBonet shows.
The calculation uses a long of 2MHz, but the others are 16 bits. Could you force that calculation with long ? f = int( 2000000L / long( TCNT1));
[edit] It is not needed to force the compiler into a 'long' calculation, it already does so.
The 'f' variable is used in an interrupt and outside that interrupt. It must be made 'volatile': volatile int f=0;
The 'f' is used in the loop, but the interrupt could happen when 'f' is only half read or half written. The ATmega328P is a 8-bit microcontroller and 'f' is a 16-bits variable. I suggest to disable the interrupts and make a copy.
noInterrupts();
int fcopy = f;
interrupts();
sprintf(msg,"Humidity:%d \n",fcopy);

What is the range that you want to measure ?
Do you know that there are good libraries to measure a frequency ? They are the FreqMeasure Library and the FreqCount Library.
[ADDED]
Try to slow down the loop with a delay. If you fill the transmit buffer of the Arduino Uno TX, then the Serial.println wait for each character if there is a place in the transmit buffer.

You wrote: “Is it, for example, allowed that the TCNT1 is cleared in an interrupt routine?” Of course, why not? “The TCCR1A is cleared, but not set to a value?” It is set to zero, which is a perfectly valid value. “Could you force that calculation with long?” That's exactly what the compiler already does as part of the usual arithmetic conversions.

I'm measuring a frequency between 5khz to 7khz, it is showing me 8-9 khz for signals in the ranges of 6500~6600 hz.  I knew about the libraries but the code was so simple that I thought it would be a piece of cake, which was not.

That's not way off, it's actually kind of OK. You are just loosing about 50 µs.

@EdgarBonet, you are correct. The compiler did make a 'long' calculation, but I like to force a long calculation in code. I like to tell the compiler what to do, instead of letting the compiler think about it, because it's so easy to make a mistake in the code. The result of clearing TCNT1 depends on the frequency range, that's why I asked.

@EdgarBonet It's way off because the number of TCNT and the division does not make sense. I usually get about 297~307 in the TCNT on the interrupts and if you divide it by hand it should not give you 8000!

So I have had asked this question on the Arduino forum and some one has fixed my code which gives me the accuracy that I expect. The problem was that the division was better not to be in the ISR routine but in the main loop. Here's the link to that answer because that guy should be credited as he helped me big time.
https://forum.arduino.cc/index.php?topic=486573.0
Thanks to all who replied to me, I have learned many things about ISR's and their limitations.

Note that the answer you got in the forum is almost good. See my expanded answer for why it's still not as accurate as it could be.

@EdgarBonet Yeah I merged his code with yours and it works very accurate, and error about 4~6 Hzs which is awesome. Thank you thank you so much.

Your approach is basically a reciprocal counter and it can work, if you start and stop the timer in the isr. The logic is essentially this:
If timer is on stop the timer and save the timer count.
Else initialize the timer and start counting.
For counting a wide range of frequencies, you may need to consider timer over flow.
Edit: any solution that reads a multi byte counter while it is running will produce the wrong results. Google atomicity to understand why.


text:
Repeatedly checking multiple "if" statements
This code is part of a long code for a robot that is both obstacle-avoiding and remote control. I am trying to get the code to check both "if" statements when the code number FF807F is received from an IR remote. When the code number is received
the program checks both "if" statements and carries out the one that is true. I want the program, once it has finished carrying out the true "if statement, to check both "if" statements again.
void loop () {
if (My_Decoder.value==0xFF807F){
 if (cm<6)
 {
  motor_stop();
  digitalWrite(backlights, HIGH);
  delay(2000);
  motor_backward();
  digitalWrite(backlights, HIGH);
  Serial.println("backward");
  delay(2000);
  motor_stop();
  digitalWrite(backlights, HIGH);
  delay(900);
  motor_right();
  digitalWrite(backlights, LOW);
  Serial.println("right");
  delay(1000);
}
if (cm>6)
 {
  motor_forward();
  digitalWrite(backlights, LOW);
  Serial.println("forward");
}
}
}

What changes My_Decoder.value? If cm is exactly 6  you want to do nothing, is that right?

I am going to assume you don't want to include cm == 6 which is why you have both cases. I would consider using a while loop instead of a singular 'if' statement in order to continuously check if those buttons are being pressed or not (while (cm<6){do this stuff}). Otherwise, it will check once and never check again.
Instead it will jump down to the next 'if' statement, it will fail and then jump to the top of the loop where it will check for the code 0xFF807F. Let me know how it goes!

if (My_Decoder.value == 0xFF807F) {
if (cm<6)

Are you wanting both "ifs" to occur? Maybe a bitwise operator like logical AND (&)?

& only makes sense if the bits are related to each other--a logical && would be used here; value == 0xFF807F && cm < 6.

This looks like a good use for a State Machine.
It would look something like this:
typedef enum State
{
  STATE_IDLE,
  STATE_THIS,
  STATE_THAT,
  STATE_OTHER
} State;

State state;

const int IR_BUTTON_1    = 0xFF807F;
const int IR_BUTTON_2    = 0x112233;
const int IR_BUTTON_3    = 0X445566;
const int IR_BUTTON_STOP = 0x778899;

void setup()
{
  Serial.begin(115200);
  Serial.println(F("setup()"));
  state = STATE_IDLE;
}

void loop()
{
  Serial.println(F("loop()"));

  switch(my_decoder.value)
  {
    case IR_BUTTON_1:
      state = STATE_THIS;
      Serial.println(F("Entered STATE_THIS"));
      break;
    case IR_BUTTON_2:
      state = STATE_THAT;
      Serial.println(F("Entered STATE_THAT"));
      break;
    case IR_BUTTON_3:
      state = STATE_OTHER;
      Serial.println(F("Entered STATE_OTHER"));
      break;
    case IR_BUTTON_STOP:
      state = STATE_IDLE;
      Serial.println(F("Entered STATE_IDLE"));
      break;
  }

  switch(state)
  {
    case STATE_THIS:
      DoThis();
      break;
    case STATE_THAT:
      DoThat();
      break;
    case STATE_OTHER:
      DoOther();
      break;
  }
}

void DoThis()
{
  Serial.println(F("DoThis()"));
}

void DoThat()
{
  Serial.println(F("DoThat()"));
}

void DoOther()
{
  Serial.println(F("DoOther()"));
}

This locks the state machine into an active state as per the OP's comment:

I want it to repeat the "void doSomething();" function until another button is pressed.

However, as Dave Newton pointed out in the comments, locking a machine into a particular active state can be dangerous, so I've edited the code to add a STOP button to transition back to the IDLE state. But this still relies on the operator pressing the STOP button to return to idle; there is no automatic return to idle which could be a hazard depending on the application.

Hm, maybe. I think if this was going to be a "non-degenerate" state machine, though, you'd have a "received input" state that then looped over the cm value until whatever its "done" condition is, then go back into a "waiting" or "processing" state, depending on what the OP's actual use-case is. As described here this is just breaking up a value check and a method call. The methods, all for it. The handling of states--dangerous, because no example of exiting a state is provided :)


text:
Infinite "while" statement
I am building a robot that is both obstacle-avoiding and remote-controlled. The robot uses an infrared remote.  When the front button is pressed the robot moves front, when the right button is pressed the robot turns right, and so on...
When a certain button is pressed the robot switches to obstacle-avoiding mode and starts to drive around. When the ultrasonic sensor detects an object 15cm away the robot turns right, reverses, and then continues moving forward. the obstacle-avoiding code has a problem, though. Here is the code:
#include <EEPROM.h>
#include <IRLib.h>
#include <AFMotor.h>
int frontlights = A1;
int backlights = A2;
int buzzer = A3;
int pingPin = A4; //setup pingpin as A4

//ir variables
int RECV_PIN = A0;
IRrecv My_Receiver(RECV_PIN);
IRdecode My_Decoder;
unsigned int Buffer[RAWBUF];

void obstacle_avoiding(){
   while (My_Decoder.value==0xFF807F && My_Decoder.value!=0xFF0AF5){  // when the automatic mode button is pressed and the stop button is not pressed do...

 motor4.setSpeed(230);
 motor3.setSpeed(230);
 motor2.setSpeed(230);
 motor1.setSpeed(230);

    long duration, inches, cm;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

  // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  delay(90);

      if(cm>15){          // if an object is greater than 10cm move forward
      motor_forward();
      Serial.println("forward");
      digitalWrite(backlights, LOW);

      }

     else if (cm<=15)     // if an object is less than or equal 10cm move backward then turn right
     {
      motor_stop();
      digitalWrite(frontlights, HIGH);
      digitalWrite(backlights, HIGH);
      digitalWrite(buzzer, HIGH);
      delay(200);
      digitalWrite(buzzer, LOW);
      delay(2000);
      motor_backward();
      digitalWrite(backlights, HIGH);
      Serial.println("backward");
      delay(500);
      motor_stop();
      digitalWrite(backlights, HIGH);
      delay(900);
      motor_right();
      digitalWrite(backlights, LOW);
      Serial.println("right");
      digitalWrite(frontlights, LOW);
      delay(400);

   }
   if (My_Decoder.value==0xFF0AF5){   //the stop button is pressed break the "while" loop and stop the robot
   break;
   motor_stop();
   }
 }
}

void loop() {
   long duration, inches, cm;
    if (My_Receiver.GetResults(&My_Decoder)){
       //Restart the receiver so it can be capturing another code
       //while we are working on decoding this one.
       My_Receiver.resume();
       My_Decoder.decode();

    //automatic code here
            else if (My_Decoder.value==0xFF807F && My_Decoder.value!=0xFF0AF5){
              obstacle_avoiding();

            }

          }

        }

The code is working however when the "while" statement becomes true it will loop infinitely not stopping even when the condition has become false. I thought while statements should loop until the condition becomes false. Am I misinformed?

side note: (My_Decoder.value==0xFF807F && My_Decoder.value!=0xFF0AF5) if My_Decoder.value is 0xFF807F then it's a fairly safe bet that it's not 0xFF0AF5 which means the condition can be simplified to (My_Decoder.value==0xFF807F)

@Andrew I had been working previously with the simplified condition you offered but with no different results.

Yes, the reason for the infinite loop is exactly what Look Alterno pointed out, the value of My_Decode.value never changes within the while loop so if the condition is true at the start then it'll remain to be true forever.  You need to fix that by somehow including updating My_Decoder within the loop. You can do that by either adding code within the while or by changing the while into an if and relying on the loop() function to create your loop. This was just a minor tidy up to remove redundant logic.

Copy/paste this part only:
void loop() {
   long duration, inches, cm;
    if (My_Receiver.GetResults(&My_Decoder)){
       //Restart the receiver so it can be capturing another code
       //while we are working on decoding this one.
       My_Receiver.resume();
       My_Decoder.decode();
        }
    //automatic code here
           if (My_Decoder.value==0xFF807F && My_Decoder.value!=0xFF0AF5){
              obstacle_avoiding();

            }

          }

        }

Please explain your solution and fix the code indentation.

I tried the above code and found that the "while" loop still runs infinitely.


text:
65 hall effect sensors as switches to be used as a keyboard with a teensy
I'm trying to wire up a silly little keyboard using hall effect sensors and magnets in a glove. The idea being only I can use the keyboard since I'll have the glove.
The sensors are 3 pin, (vcc, gnd, and an output that sends 5v out when a magnetic field is present. I don't have anywhere near enough pins on the teensy for all the sensors. Could I just use several port expanders? Are there issues with using 4 or 5 at once? How many keys could be pressed at a time?
Is there a better option than all those expanders?
Also I know that this keyboard will be ugly and completely impractible to use regularly, but I thought it would fun to show off.

I just asked a similar question. It sound like if you used a matrix with output legs in a line tied to a shared Arduino pin, any triggered sensor in the line will drop the whole thing LOW so you could scan rows/cols to figure out what's pressed. Instead of powering rows one by one and paying the 150ms penalty mentioned by @Jot below, you route all rows/columns to digital input with INPUT_PULLUP and read them that way. Hope that helps!

Hmm that sounds way better than my current workaround. I would assume I could just use diodes to avoid ghosting? Also in this configuration there needs only be one pin per cop and one per row right?

Also, is the input_pullup really needed if the pins are already pulled up by the resistor?

I don't think so, as long as they are pulled up. My understanding is that INPUT_PULLUP is just a convenience (not requiring extra components). Now that you ask, I think I ran across a post/comment somewhere suggesting physical resistors vs. INPUT_PULLUP, but I don't recall the reasoning at the moment.

[Completely rewritten answer]
That seems fun. But why 65 keys ? with 64 keys it is easier.
You have to test the sensitivity of the hall switches with the magnets to know how far apart the keys must be. Perhaps they only work with strong magnets or perhaps a number of them are activated when the glove is near.
With hall switches, there are 65 digital signals from the sensors.
The most common way to create more digital inputs is to use shift registers. For example with the 74HC165. Nick Gammon has the best tutorial of the 74HC165 with daisy-chain.
There is also an example is with the CD4021 and the ShiftIn function, but the 74HC165 is mostly used.
The shift registers can be daisy-chained, they are made for that.
Your AH1807 has a open-drain output. That means you need 65 pullup resistors.
It is not possible to connect all the outputs and turn them on one by one, since it requires 150ms to wake up.
Another option is using multiplexers. It can be used for analog and for digital signals. For example with four 16-to-1 multiplexers you can create 64 inputs going to 4 pins. The best multiplexer tutorial is once again written by Nick Gammon.
With four analog multiplexers of 16-to-1 you would require only 4 pullup resistors after the multiplexer. I think it is better to use a resistor per hall sensor (65 pullup resistors).
When using reed switches (those tiny glass tubes, used in house alarms), they can be set in a matrix/grid with rows and columns and the Keypad library. For example 10*7 requires 17 pins. The Keypad library allows that multiple keys are pressed at the same time.

I've seen that tutorial and read a little bit on using a matrix for keyboards. If I'm not mistaken, with a physical switch, it pulls the columns to low and rows to high and has 2 connectors one for rows and one for columns. The sensor I have only has one output leg so all my columns and rows would be connected to the same output leg right?

Oops, I might have made a big mistake. I was thinking about reed switches. Can you tell the type of the hall switches ? Perhaps I will remove my answer.

This is the sensor in question. https://www.digikey.com/product-detail/en/diodes-incorporated/AH1807-P-B/AH1807-P-B-ND/3829348

Wow, thanks for the detailed response. It doesn't have to be 65, I can get it to 64 I'm sure. I'll read both of those tutorials and see which one works best. I'll see if I can find some Reed switches to play with too, that way I could use some of the existing firmware for keyboards.


text:
4-20 milliamp to volts to pressure maths
I am measuring pressure in bars from OsiSense™ XMLP pressure sensor (4-20 milliamp) on a arduino uno.  When the machine im measuring pressure on is switched off the reading is 0v as expected.
When the machine is on (the sensor is on) the reading is 1v as expected.
When the machine is on and hydraulics are active the voltage fluctuates as expected.
The problem I have is I don't know the maths to translate the voltage to bar pressure.
From a previus question i've asked from 0v to 5v the equation is:
// This is for the DEFAULT 5V analog reference.
// v = the voltage at the pin in Volts.
// p = the pressure in bar.
// Note that 'bar' is the pressure relative to the
// normal atmospheric pressure at that moment.
float v = (float) analogRead(A0) / 1024.0 * 5.0;
float p = v / 5.0 * 100.0;"

Is it just a matter of changing the equation to take into account the 1v when the sensor has power and then dividing by 4 instead of 5:
RawVoltage = (float) analogRead(A0) - 1;
float v = RawVoltage / 1024.0 * 4.0;
float p = v / 5.0 * 100.0;"

Please add a circuit (wiring). Also explain how you reasoned about dividing by 4 instead of 5. Last which model are you using; the pressure range depends on the device. 4-20 mA is 0-100% of the pressure range.

Thanks for getting back to me so quick.  I'm sure its something easy im missing.  The pressure sensor reads 0 to 100 bar.  0mA to 20mA is 0v to 5v range which is %100 of the possible readings.  4-20 mA is 1v to 5v and is 80% or 4v.  The first 1v (0 to 4mA) just tells us the sensors has power and is working ok and reading 0 bar.  What I need to workout is 0 bar to 100 bar (4 mA to 20 mA).
you can see a diagram on the post here: https://arduino.stackexchange.com/questions/45485/reading-4-to-20ma-pressure-sensor-using-uno

If I understand your question correctly, when the sensor is on,

4 mA (1 V on the Arduino) means 0 bar
20 mA (5 V on the Arduino) means 100 bar.

Is that correct?
If that is correct, there you just have to linearly map the voltage
range to the pressure range. The equation is
P = (v − 1 V) / 4 V × 100 bar
or, in C++:
float v = analogRead(A0) / 1024.0 * 5.0;  // in volts
float p = (v - 1) / 4 * 100;              // in bars


text:
Which sensor i can use to transmit some values from Arduino Uno to phone using bluetooth?
I want to transmit some values from arduino uno to my phone using bluetooth.
Which sensor i can use?I want to see some options because i'm a little bit uncertain.Thanks to all which can give me an advice !  :)

So you want to know how to send a text file from the arduino to the phone?

It's not a sensor, its a module. A quite popular module is the HC-05. It's a very simple to use module with a lot of support by the community. Cheap and great for projects.


text:
Arduino IDE in conflict with pyserial for use of serial port in OSX Yosemite
I'm trying to communicate with an Arduino Uno via pyserial using a code that I wrote for Ubuntu. However, when I try to use the same code in OSX Yosemite after identifying the serial port for the case of OSX, it doesn't work. This is the offending line:
In [32]: ser = serial.Serial('/dev/cu.usbmodem1421', 9600)

If I run the above line when the Arduino IDE is not running there is no error message, but the Arduino doesn't do anything (the Arduino IDE Serial Monitor must be open in order for the code to work). However, if I open the Arduino IDE and use the Serial Monitor (which works fine, i.e. it shows data that the Arduino is sending), I get the following error message:
SerialException: [Errno 16] could not open port /dev/cu.usbmodem1421: [Errno 16] Resource busy: '/dev/cu.usbmodem1421'

If I run lsof | grep /dev/cu.usbmodem1421 then I get that the only program using said port is Arduino IDE:
Arduino   2012 germanchaparro   94u     CHR               18,7   0t15249    1285 /dev/cu.usbmodem1421

Clearly OSX is not letting Arduino IDE and pyserial to use the serial port (to which the Arduino UNO is connected) at the same time. I don't know how to fix this, and it's especially frustrating since Ubuntu doesn't put up a fight.
Any ideas?

You need to work out why Python isn't working. There is no reason to need the IDE terminal open unless your code is doing things very wrong.

You're right, I can get pyserial to work without the IDE monitor open, although I'm having a hard time printing out the serial output from the Arduino. It seems it's mostly a matter of giving the code enough time between pyserial r/w instructions. It just baffles me how different (and simpler) pyserial works in Ubuntu.

Ok, I solved it. First I stopped using the IDE serial monitor as Majenko suggested, and focused on getting the Arduino readings within the python code. Besides trying to use the python code and the IDE monitor at the same time (which apparently you can do in Ubuntu but not in OSX), the original problem was that my python code was not clearing the serial buffer in the r/w process. In order to do this, I wrote the following function to be called before and after a serial write:
 ser = serial.Serial('/dev/cu.usbmodem1421', 9600)

 def readarduino(ser):
    did=True
    while ser.inWaiting(): # Check number of characters left in buffer
        if did and ser.inWaiting() < 490: # Select last 500 characters in buffer
            for i in range(6):
                print ser.readline() # Print 6 lines in buffer
            did = False
        ser.readline()  # Clear buffer line by line until ser.inWaiting goes to 0

This ensures that the buffer is clear whenever I am writing to the Arduino.
This solution works for OSX Yosemite and Ubuntu 14.04


text:
How to check if a LED is on?
I have a circuit board / device that can be in different states. It indicates in which state it is by turning on one of three LED's. Now I want to use an ESP8266 to tell me (over the network) the current state. What kind of circuit would I need for this? (I have thought about using photodiodes, but I would much rather solder something directly to the board)

Can you measure the voltage that the "circuit board" uses to switch the LED on and off?

If you are talking about the LED voltage drop, its 2.7v.

What voltage does the "circuit board" operate at? Is it the same as the ESP8266?

As its powered via USB, i assume its operating at 5v.

If the device turning the LEDs on / off runs on 3.3 Volts (has ground to 3.3 Volts outputs), then you might consider directly connecting the 3.3 Volt outputs to the GPIO pins of the ESP8266.  If the device turning the LEDs on / off runs on higher voltages consider either using the appropriate level shifter or the appropriate optical isolator:

An optocoupler's input takes e.g. 1.7V as Vf :  With a 100 Ohms resistor you add another 10 mA load to the  LED's 2.7V .  Pin 4 = GND,  Pin3 = INPUT_PULLUP should be LOW when LED is on, and HIGH when off.


text:
Running in loop or once according to a slide switch position
I have a question.
I made a system which includes a servo, a stepper and a wiper motor :)
All these parts has one job to do and I can code it. But, I want to make 2 modes in this system Single Operation, Loop operation.
for example position 1-single operation, 2-loop operation.
I can code the loop operation thanks to arduino syntax :)
But I cannot code single one. I can read switch state detection.  I want to do exactly same things, but only one time when slide switch on the position.
The code is really long and it includes Turkish defines. If you need to see the code, let me know.

Let's assume the switch is on pin 9, that the pinMode() has already been set, and that the switch reads HIGH for loop operation.
#define MODE_SWITCH  9
#define DO_LOOP  HIGH

// This loop will execute once if the mode-switch is off, or
// will execute continously if the mode-switch is on:
do {
  servo_things();
  stepper_things();
  motor_things();
} while( digitalRead(MODE_SWITCH) == DO_LOOP );

in C/C++, 'do-while' loops always execute at least once, since the condition isn't tested until after the first pass through the loop. If the 'while' condition is satisfied (or TRUE), the loop will execute again, otherwise the loop will exit.

I think you should do a digitalRead() inside the while condition. I think you meant that and only wrote it simplified, but since this isn't written in pseudo code, others might copy the code directly, what means to compare 9 to 1, which is always false.

Good catch, @chrisl - that was exactly right. Tthanks. Fixed now.

I'll try this. Thanks to you