body:
<!-- language-all: lang-C++ -->

I googled solutions and tried, but I still cannot get it working.

I've tried BlinkwithoutDelay.

I feel it is very confusing to track timing of two motors (i.e., step, direction, speed) for the following routine loop:

* step 1: run motorA_forward() for 10 seconds;
* step 2: run motorAB_stop() for 1 seconds;
* step 3: run motorB_backward() for 3 seconds
* step 4: run motorAB_stop() for 1 seconds
* step 5: run motorA_backward() for 10 seconds
* step 6: run motorAB_stop() for 1 seconds

Please help me on this!! I really appreciate your time and comments.

Thank you.

The following is my working code.

    // ----------LIBRARIES--------------

    #include <Wire.h>
    #include <LIDARLite.h>
    LIDARLite myLidarLite;

    // ----------CONSTANTS--------------

    const int motorA_pin_1 = 8;           // the pin numbers for the motors
    const int motorA_pin_2 = 11;
    const int motorA_pin_speed = 9;
    const int motorB_pin_1 = 12;
    const int motorB_pin_2 = 13;
    const int motorB_pin_speed = 10;

    //------------VARIABLES--------------

    byte motorA_state_1 = LOW;             // used to record whether the motots are on or off
    byte motorA_state_2 = LOW;             // LOW = off
    byte motorB_state_1 = LOW;
    byte motorB_state_2 = LOW;

    int currentMillis               = 0;     // stores the value of millis() in each iteration of loop()
    int motorA_Forward_Interval     = 5000;  // will store last time the motor was moved
    int motorA_Backward_Interval    = 5000; // will store last time the motor was moved
    int motorA_Stop_Interval        = 2000;  // will store last time the motor was moved
    int motorB_Stop_Interval        = 2000;  // will store last time the motor was moved
    int motorAB_BreakTime_Interval  = 2000;

    unsigned long motorA_Forward_Timer      = 0;     // will store last time motorA start was updated
    unsigned long motorA_Backward_Timer     = 0;     // will store last time motorA start was updated
    unsigned long motorB_Forward_Timer      = 0;     // will store last time motorA start was updated
    unsigned long motorB_Backward_Timer     = 0;     // will store last time motorA start was updated
    unsigned long BreakTime_timer   = 0;     // will store last time motorA/B break time was updated

    //------------INITIALIZATION--------------

    void setup()
    {
      Serial.begin(115200);
      myLidarLite.begin();

      pinMode(motorA_pin_1,OUTPUT);         // set the motor pins as output:
      pinMode(motorA_pin_2,OUTPUT);
      pinMode(motorA_pin_speed,OUTPUT);
      pinMode(motorB_pin_1,OUTPUT);
      pinMode(motorB_pin_2,OUTPUT);
      pinMode(motorB_pin_speed,OUTPUT);

    }

    //------------LOOPING----------------------
    // Notice that none of the action happens in loop() apart from reading millis()
    // It just calls the functions that have the action code

    void loop()
    {
        Serial.println(myLidarLite.distance());

        unsigned long currentMillis = millis();

        motorA_forward();  // for 10 seconds
        motorAB_stop();    // for 1 seconds
        motorB_backward(); // for 3 seconds
        motorAB_stop();    // for 1 seconds
        motorA_backward(); // for 10 seconds
        motorAB_stop();    // for 1 seconds

    }

    //------------SUBROUTINE----------------------

    void motorA_forward()
    {
      if(currentMillis - motorA_Forward_Timer <= motorA_Forward_Interval)
      {
        motorA_state_1 = HIGH;   // Turn motor A on - backward
        motorA_state_2 = LOW;  //
        motorB_state_1 = LOW;   // Turn motor B off
        motorB_state_2 = LOW;   //

        analogWrite(motorA_pin_speed,255);
        digitalWrite(motorA_pin_1,motorA_state_1);
        digitalWrite(motorA_pin_2,motorA_state_2);
        analogWrite(motorB_pin_speed,255);
        digitalWrite(motorB_pin_1,motorB_state_1);
        digitalWrite(motorB_pin_2,motorB_state_2);

        motorA_Forward_Timer = currentMillis;
      }
    }

    void motorA_backward()
    {
        if(currentMillis - motorA_Backward_Timer <= motorA_Backward_Interval)
      {
        motorA_state_1 = LOW;   // Turn motor A on - backward
        motorA_state_2 = HIGH;  //
        motorB_state_1 = LOW;   // Turn motor B off
        motorB_state_2 = LOW;   //

        analogWrite(motorA_pin_speed,255);
        digitalWrite(motorA_pin_1,motorA_state_1);
        digitalWrite(motorA_pin_2,motorA_state_2);
        analogWrite(motorB_pin_speed,255);
        digitalWrite(motorB_pin_1,motorB_state_1);
        digitalWrite(motorB_pin_2,motorB_state_2);

        motorA_Backward_Timer += currentMillis;
      }
    }

    void motorB_forward()
    {
        motorA_state_1 = LOW;   // Turn motor A off
        motorA_state_2 = LOW;   //
        motorB_state_1 = HIGH;  // Turn motor B on - forward
        motorB_state_2 = LOW;   //

        analogWrite(motorA_pin_speed,255);
        digitalWrite(motorA_pin_1,motorA_state_1);
        digitalWrite(motorA_pin_2,motorA_state_2);
        analogWrite(motorB_pin_speed,255);
        digitalWrite(motorB_pin_1,motorB_state_1);
        digitalWrite(motorB_pin_2,motorB_state_2);

        motorB_Forward_Timer = currentMillis;
    }

    void motorB_backward()
    {
        motorA_state_1 = LOW;   // Turn motor A off
        motorA_state_2 = LOW;   //
        motorB_state_1 = LOW;   // Turn motor B on - backward
        motorB_state_2 = HIGH;  //

        analogWrite(motorA_pin_speed,255);
        digitalWrite(motorA_pin_1,motorA_state_1);
        digitalWrite(motorA_pin_2,motorA_state_2);
        analogWrite(motorB_pin_speed,255);
        digitalWrite(motorB_pin_1,motorB_state_1);
        digitalWrite(motorB_pin_2,motorB_state_2);

        motorB_Backward_Timer = currentMillis;
    }

    void motorAB_stop()
    {
        motorA_state_1 = LOW;   // Turn motor A off
        motorA_state_2 = LOW;   //
        motorB_state_1 = LOW;   // Turn motor B off
        motorB_state_2 = LOW;  //

        analogWrite(motorA_pin_speed,0);
        digitalWrite(motorA_pin_1,motorA_state_1);
        digitalWrite(motorA_pin_2,motorA_state_2);
        analogWrite(motorB_pin_speed,0);
        digitalWrite(motorB_pin_1,motorB_state_1);
        digitalWrite(motorB_pin_2,motorB_state_2);

        BreakTime_timer = currentMillis;
    }

title: run two motors in turns without using delay()

Answers: 2

body:
<!-- language-all: lang-C++ -->

    int currentMillis               = 0;     // stores the value of millis() in each iteration of loop()
    ...

    void loop()
    {
        Serial.println(myLidarLite.distance());
        unsigned long currentMillis = millis();

You have **two** `currentMillis` variables. The global one never changes. You change a **different** one inside `loop`.

---

Remove the data definition. eg.

    void loop()
    {
        Serial.println(myLidarLite.distance());
        currentMillis = millis();  // change the global variable

---

Also make the **global** one unsigned long:

    unsigned long currentMillis               = 0;     // stores the value of millis() in each iteration of loop()

body:
This is a classic example where Object Oriented Programming (OOP) can make your life so much easier.

The principle behind OOP is to define a *Class* which contains all the actions you want to perform on something - in this case a motor.  The *Class* contains all the instructions on how to do things like set the motor speed, the direction, start it, stop it, etc.

From that *Class* you then create *Objects*.  The beauty is there is only one *Class* which has the abstract concept of "Motor Control", but that *Class* is used to create one *Object* for each motor you want to control.

A *Class*, and hence the *Objects* derived from it, are all completely self contained, which makes it so much easier to manage.  All the variables associated with a single motor are wrapped up inside the *Class* and you don't need to worry about unique names for them all on a per-motor basis.

For example, you might define a class like this:

    class Motor {
        private:
            int _speedPin;
            int _directionPin1;
            int _directionPin2;

        public:
            Motor(int sp, int dp1, int dp2) {
                _speedPin = sp;
                _directionPin1 = dp1;
                _directionPin2 = dp2;
            }
            void begin() {
                analogWrite(_speedPin, 0);
                pinMode(_directionPin1, OUTPUT);
                pinMode(_directionPin2, OUTPUT);
                digitalWrite(_directionPin1, LOW);
                digitalWrite(_directionPin2, LOW);
            }
            void forward() {
                digitalWrite(_directionPin1, HIGH);
                digitalWrite(_directionPin2, LOW);
            }
            void reverse() {
                digitalWrite(_directionPin1, LOW);
                digitalWrite(_directionPin2, HIGH);
            }
            void speed(int speed) {
                analogWrite(_speedPin, speed);
            }
            void stop() {
                analogWrite(_speedPin, 0);
                digitalWrite(_directionPin1, LOW);
                digitalWrite(_directionPin2, LOW);
            }
    };

Everything you need to control a motor is in there.  Then you could use that to create two motor objects:

    Motor leftMotor(3, 4, 5);
    Motor rightMotor(6, 7, 8);

You provide the pins that control the motor to the *constructor* of the object - that is pin 3 is the speed pin of the first motor, and pins 4 and 5 are the direction control pins, etc.

You can now control the motors very simply.  Configure the pins by calling the begin function defined in the class above:

    void setup() {
        leftMotor.begin();
        rightMotor.begin();
    }

And now you can use similar decision making as normal to decide when to do what.  The main difference is that your motor control code now looks as simple as:

    leftMotor.forward();
    rightMotor.reverse();

or

    leftMotor.stop();
    rightMotor.forward();
    rightMotor.speed(30);

You then end up with a program that is much cleaner and easier to follow.  And adding a third or forth motor is as simple as defining more Motor objects with their pins.

This video is a good introduction to what OOP is and how it differs from the "traditional" approach:

* https://www.youtube.com/watch?v=MTfWr7o7Q4U


body:
This code we are using only one motor and one hc-sr04 ultrasonic sensor, the code is shown below:

<!-- language-all: lang-C++ -->

    #define trigPin 7
    #define echoPin 6
    #define motorPin 5

    void setup()
    {
      Serial.begin(9600);// to use the serial monitor
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(motorPin, OUTPUT);
    }

    void loop()
    {
      int duration,distance;
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      distance = (duration/2)/29.1;
      Serial.print(distance);//to print the distance on the serial monitor
      Serial.println("cm");

      // to make the motor vibrate depending on the distance
      // if the ultrasonic sensor is too far from the obstacle it will vibrate slowly
      // if the ultrasonic sensor is very close to the obstacle it will vibrate very fast

        if(distance <= 60 && distance >= 45)
        {
          // to make the motor vibrate
        digitalWrite(motorPin, HIGH); // making the motor on

        delay(200);
        digitalWrite(motorPin, LOW);// making the motor off
        delay(200);
        }

        else if(distance < 45 && distance >= 30)
        {
        digitalWrite(motorPin, HIGH);
        delay(100);
        digitalWrite(motorPin, LOW);
        delay(100);
       }
        else if(distance < 30){

        digitalWrite(motorPin, HIGH);
        delay(50);
        digitalWrite(motorPin, LOW);
        delay(50);
      }
      else
      {
        digitalWrite(motorPin, LOW);
      }
    }

We want you to tell us your comment about the code.

And we want to add two more motors and two ultrasonic sensors, one of them in the left and the other in the right.

We want you to help us in the code, because we don't know how we can change it for two other motors.

title: How do I use 3 Hc-sr04 ultrasonic sensors to control 3 vibration dc motor?

Answers: 1

body:
There's a few things you need to consider when making multiple things happen at the same time.

Firstly is timing. You can't make two things happen concurrently with different timings if you have `delay()` in there, since nothing else can happen while `delay()` is executing.  So you have to get rid of all `delay()` calls and replace them with examining the difference between successive calls to `millis()`.

For instance, imagine you're in the kitchen and you want to boil and egg and make a cup of tea at the same time.  You fill the kettle and turn it on.  You put a pan of water on the stove with an egg in it to boil.

Now you could sit and stare at the egg until it's boiled enough for you to eat, but what happens to the kettle while you're doing that?  It's boiled, turned itself off, and started to go cold.

So instead you put the egg in the pan and look at the clock.  Then you think "in 5 minutes I will take the egg out of the boiling water".  You might set an alarm for 5 minutes time if you have one, or you may keep glancing at the clock periodically to see if the 5 minutes have past yet.  Meanwhile the kettle has boiled and you've made your cup of tea.

Then the 5 minutes have passed.  You know that because *you remembered what time you put the egg on to boil* and *you know what the time is now*, so you can subtract one from the other to find that 5 minutes have passed.

Now let's make it a little more complex.  Imagine you want two eggs - one soft boiled and one hard boiled.  The hard boiled one may want 8 minutes, the soft boiled one 5 minutes.

So you put one egg on to boil and remember the time.  Roughly three minutes later you put the other egg in and also remember that time.

Once enough time has passed that the first egg has been in 8 minutes you take it out.

Once enough time has passed that the second egg has been in 5 minutes you take it out.

You have had to remember two start times which you then compare separately to decide what to do with each egg when.

To translate that to your program - you have to remember a start time for each action for your motors, along with the state of the motors - and when the right time has elapsed you change the state of the motor (motor on -> motor off - egg in pan -> egg on plate) and remember the time at which you changed the state so you can know when to change the state again.

That's exactly what the BlinkWithoutDelay example does to make an LED change state (on -> off -> on) at certain times by remembering *when* it last changed state so you know *when* to change the state next.


body:
Im using a potentiometer to control the speed of two generic 6-8V DC motors. The potentiometer input is scaled from 0-1023 to 0-255, I then use the analogWrite() function to write this value to the enable pins on my L293D motor controller.

Im sure this should control the speed but it doesn't, I have the code printing the value it sends to the enable pins and this is correct, but no speed increase, the motors either move at one speed or don't move at all. My enable pins are 12 and 13 on my Arduino Uno, previously 5 and 6 but I moved them to see if that was the problem.

Is there a problem with the PWM frequency maybe? I don't understand why it won't go faster and slower after days of troubleshooting.. The inputs are all set correctly, allowing both motors to move in the forward direction..

    int Speed = analogRead(speedChange);
    int SpeedMap = map(Speed,0,1023,0,255);
    analogWrite(enable1, SpeedMap);
    analogWrite(enable2, SpeedMap);

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

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

Its a long shot but does anyone know enough about PWM control on DC motors to think of any things I may be missing while trying to do this? Ill provide any info ASAP, thanks

title: Varying motor speed with the L293D

Answers: 2

body:
Although I am still figuring things out, but i hope the following things help:

http://www.solar4rschools.org/sites/default/files/robotic-sunflower-lesson4-handout4.pdf

The problem, as far as I think is that the enable pins are the ones which are supposed to help you control the speed. Please connect them to the PWM ports on your Arduino/any other device you may be using for your project.

Or, you can simply write a code which keeps on disabling and enabling the enable pins to get the desired speed (that's what PWM is supposed to do but you can try it this way, at least).

body: I guess you're not using the designated PWM pins provided on the Arduino Board, anyhow I suggest you read this instructible: http://www.instructables.com/id/Arduino-DC-motor-speed-and-direction-L293D/step2/L293D-Pin-Layout/ ,Perhaps this can help you in making proper connections and also help you with the code :)


body:
This is not a duplicate of my other question. This question deals with reading specific data within a serial stream. The other question deals with reading and adding data into a manageable data string.

What I'm trying to do is send a command to serial, get the response, and put it into a string, and then break that string up into usable parts of data.

The problem I'm having, is there is a delay between the time the serial command is sent, and the response. meaning the serial data isn't being captured before the function moves onto the next line. Using delay() doesn't appear to work, as i believe it halts everything for that delay period.

What I'm hoping to do, is read the data from serial and if the character '<' is received, place it, and everything after it into the buffer until the character ">" is received.  After the last character is received, and placed into the buffer, continue on with the script.

Unless of coarse someone has a better idea on how to approach this.
i would also like to note that this is just a part of a larger project. If you need to see the entire project, please let me know and i will provide a link where you can download it.

The string i'm expecting as a response would be similar to this:

    <Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>

Here is the code i have so far:

    float mx;
    float my;
    float mz;
    float wx;
    float wy;
    float wz;
    String dAlarm;
    char buffer;
    void gPos() {
      Serial1.print("?\n");
      buffer = Serial1.read();
      char string[80];
      string[buffer];
      char *alarm = strtok(string, ",");
      char *mposX = strtok(NULL, ",");
      char *mposY = strtok(NULL, ",");
      char *mposZ = strtok(NULL, ",");
      char *wposX = strtok(NULL, ",");
      char *wposY = strtok(NULL, ",");
      char *wposZ = strtok(NULL, ">");
      alarm += 1;
      mposX += 5;
      wposX += 5;
      mx = strtod(mposX, NULL);
      my = strtod(mposY, NULL);
      mz = strtod(mposZ, NULL);
      wx = strtod(wposX, NULL);
      wy = strtod(wposY, NULL);
      wz = strtod(wposZ, NULL);

      if (strcmp(alarm, "Idle") == 0) {
        dAlarm = "Idle";
      } else if (strcmp(alarm, "Run") == 0) {
        // Something to do when Busy
        dAlarm = "Run";
      } else if (strcmp(alarm, "Hold") == 0) {
        // Something to do when Busy
        dAlarm = "Hold";
      } else if (strcmp(alarm, "Door") == 0) {
        // Something to do when Busy
        dAlarm = "Door";
      } else if (strcmp(alarm, "Home") == 0) {
        // Something to do when Busy
        dAlarm = "Home";
      } else if (strcmp(alarm, "Alarm") == 0) {
        // Something to do when Busy
        dAlarm = "ALARM!";
      } else if (strcmp(alarm, "Check") == 0) {
        // Something to do when Busy
        dAlarm = "Check";
      }
      dispPos();
    }

    void dispPos() {
      int state = 0;
      int x = analogRead (0);
      if (x < 800) {
        state = 1;
      }
      if (state == 1) {
        dPos = false;
      }

      if (dPos == true) {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("X");
        lcd.print(mx);
        lcd.setCursor(8, 0);
        lcd.print("Y");
        lcd.print(my);
        lcd.setCursor(0, 1);
        lcd.print("Z");
        lcd.print(mz);
        lcd.setCursor(8, 1);
        //lcd.print(" ");
        lcd.print(dAlarm);
        delay(3000);
      } else {
        mainMenu();
      }
    }

title: How can i read serial data into a string until a certain character is recieved?

Answers: 1

body:
What you need to do here is implement a small *finite state machine*.

Basically you need to look at each character as it comes in and make a decision what to do with it *depending on what state you're in at the moment*.

Basically the operational decisions you need to make are:

* Is the character a < and am I currently not reading a string?
  * Yes, start reading the string.
* Is the character a > and am I currently reading a string?
  * Yes, finish reading the string and process it
* Is it any other character and I am currently reading the string?
  * Yes, add it to the buffer.

So you can see there some common questions:

* What is the character?
* What am I doing at the moment?

So you need to have a simple state variable that remembers if you're reading the string or not, and something to say where in the buffer you are so you know where in the buffer to add any incoming characters.

    boolean readingString = false;

A simple true/false will suffice to depict if we're reading the string or not.  Start off not reading the string.

    char buffer[80] = "";

A buffer to store the text - maximum of 80 characters (*including the NULL terminating character*)

    int charPointer = 0;

Something to know where in the buffer are currently.

Now to read the characters:

First get the next character from the serial port:

    loop() {
        if (Serial.available()) {
            int incoming = Serial.read();

Now decide what to do with it.  We have a number of possible situations, some of which can be combined into single options.  For instance, if we get a "<" while reading a string it's an error condition - but do we really care?  It could be that we lost the end of the last string and have just started a fresh one - so we can just treat it as the start of a string regardless of what state we're in.  Let's use a `switch` for this since it's nice and tidy:

            switch (incoming) {
                case '<':
                    readingString = true; // Start reading string
                    charPointer = 0; // Set the buffer pointer to the start
                    buffer[0] = 0; // Make the string empty
                    break;

                case '>':
                    if (readingString) {
                        processBufferData(); // Do something with the buffer
                    }
                    readingString = false; // Finish reading
                    break;

                default: // Anything that's not > or <
                    // If we are reading the string and the buffer isn't full
                    if (readingString && charPointer < 78) {
                        // Add the character to the buffer and increment the pointer
                        buffer[charPointer++] = incoming;
                        buffer[charPointer] = 0; // Don't forget to terminate the string
                    }
            }
        }
    }

So the reception of a < starts the string reading, the reception of a > stops it and triggers the processing of the string, and anything else (while we are reading the string) gets added to the buffer.


body:
The author of the PinChangeInt library and the EnableInterrupt library states at [github][1]:

> When the PinChangeInt was in a .h and .cpp file, the Arduino IDE tried
> to compile it twice. I have a technique that you can use- #define
> LIBCALL_ENABLEINTERRUPT - that if you put it ahead of your #include in
> all files but the sketch, then you should be able to use the library
> without conflicts. If you know how to make it work in another way-
> remember, this is a library and will not compile in the same directory
> as the sketch and any other .h/.cpp/.ino files- then I'm all ears.

I came there, because both libraries failed to build with linker errors due to double definitions. So far so good. I split the PinChangeInt library in .h and .cpp myself and it compiled flawlessly. I did not try to split the other library yet because it looks like much work to me.

So now my question(s): Is GreyGnome right with his statement, that library code gets compiled twice when split in code and headers? And if so, what are the consequences? Memory waste? Runtime errors? What about the many other (working) libraries exhibiting separate code and header files?

  [1]: https://github.com/GreyGnome/EnableInterrupt/issues/13

title: Arduino IDE not handling library code correctly?

Answers: 2

body:
Header files are parsed by the preprocessor and the compiler wherever they are included.

There's nothing weird about that.
One can avoid multiple inclusions by using header guards.
That's pretty standard too.

I have not looked at the library, but, for example,  a typical error is to _not_ declare variables as extern in the header and instead leave the real declaration in the header, which will lead to multiple instances, possibly clashing at link time.
Variables that are part of the library API should be declared as extern in the header and the real declaration should be done only in the .C/.CPP file.

Interrupts are an even more special case: the AVR gcc relies on very specific names to identify interrupt handlers and each of them can be present at most once.
So there are even more chances for having linker problems, if not declared correctly.

body:
To elaborate on your comment ~

An easy way to prevent multiple definitions from re-inclusion of the same header file is to ensure it's only defining things once.

e.g. my_header.h

    #ifndef __MY_HEADER_H__
    #define __MY_HEADER_H__

    // some header code.

    #endif //#ifndef __MY_HEADER_H__

When the header is *first* compiled, the definition of `__MY_HEADER_H__` gets created by the compiler due to the 2nd line of the file.  On subsequent compiles, which are caused by including the same header in more files, the 1st line '#ifndef' conditional skips everything down to the '#endif'.

When you write (or split) C / C++ code, it's common to wrap the class and function definitions (which go in the .h header file) in these compilation control blocks, and then the .c/.cpp file only gets the function bodies.

e.g.: my_rgb.h ~

    #ifndef __MY_RGB_H__
    #define __MY_RGB_H__

    #include <stdint.h>

    uint32_t packRGB(uint8_t r, uint8_t g, uint8_t b);

    class RGB
    {
    public:
        RGB(uint8_t r, uint8_t g, uint8_t b);

        void toGreyscale();

    private:
        uint8_t red;
        uint8_t green;
        uint8_t blue;
    };

    #endif //#ifndef __MY_RGB_H__

and my_rgb.cpp

    #include "my_rgb.h"

    // Note: this would typically be a member function
    // but is separate to show a standalone function definition.
    uint32_t packRGB(uint8_t r, uint8_t g, uint8_t b)
    {
        uint32_t packed;

        packed = (r << 24) | (r << 16) | b;

        return packed;
    }

    RGB:RGB(uint8_t r, uint8_t g, uint8_t b)
    {
        red = r;
        green = g;
        blue = b;
    }

    void RGB::toGreyscale()
    {
        uint8_t grey = 0.2126 * (float)r + 0.7152 * (float)g + 0.0722 * (float)b;
        r = g = b = grey;
    }

Including the header file multiple times will give "redefinition" errors at __compile time__.  Including the same function multiple times will give double definitions at __link time__.

If you stick to this method of laying out .h and .c/.cpp files you will never have a problem with multiple definitions on your own files.  (Unless you re-define a library function by accident, etc.)

Of course it's ok (and quite common) to define short little functions in the header/.h file too. (The compiler typically generates these as inline code though.)  I'm not trying to explain the complete workings of headers & .C files, just presenting you a method which will *always* prevent multiple definition problems.


body:
Distance is about 3m. IR or visible light - does not matter.

 It is possible that object/obstacle can be shiny, so for correct detection necessary large amount of reflected light.

Maybe for this task better to use specific retroreflector?

**UPDATE:**

there will be two sensors with distance about 3-4 cm between.
Object must cross 1st sensor's reflector but do not cross the 2nd one.

The scheme of this sensor should be this:
[![Scheme of sensor][1]][1]

But the use will be this:

[![scheme of use][2]][2]

  [1]: https://i.stack.imgur.com/TXiTh.png
  [2]: https://i.stack.imgur.com/WYjFY.png

title: Which sensor is best for obstacle detecting with retroreflector?

Answers: 2

body:
I think the question is worded to get a specific answer; I do not know if this is the answer you want. I'll give you that answer first:

I'd say an infrared LED, and an infrared detector.

Strobe the LED, then measure the difference between when it's (known to be) on, and when it's (known to be) off, to compensate for ambient light.

However, if I was doing this, I'd consider an ultrasound sensor - no retroreflector needed; instead you get the distance to the (obstacle or reflector).

body:
I think you're better off with a set-up like this.

*A shiny object might bounce the laser as if it were a mirror.
But we wan't to know if the laser was interrupted.*

So. If we place the sensor on the other side, we can accurately say if the light reaches the sensor. Thus if there is an object between (shiny or not).

*But what if another light-source shines into my sensor? It'll think that there is no object.*

We can encapsulate the sensor, so that only light from the direction of the laser can shine into it. And we can filter out other light "colors".
Also the strength of the laser should be bigger as any other ambien light (not too strong also). You could even choose to make the laser pulse a specific pattern and let the sensor check if it's right.

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

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


body:
I've been trying to control a relay with a GSM shield for an Arduino project. I haven't had any success with either the Software Serial or the GSM library. I've declared the GSM variable in debug mode and it gives me the error AT%.
Using Software Serial, it hangs at SIM900.read().
The SIM card connects to the network, I can see that on the board - the LED flashes every 3 seconds and gives me signals for incoming calls and SMSs.

I can't tell if the error is with the SIM card, the connections to the Arduino board, the power supply (12V) or something completely different. Here are the two code examples I'm using with the different libraries.

Anyone else getting this error? What is the best way to make it go away?

Thanks in advance for any help!

**SoftwareSerial.h**

    #include <SoftwareSerial.h>
    char inchar; // Will hold the incoming character from the GSM shield
    SoftwareSerial SIM900(7, 8);

    int Relay1 = A2;
    int Relay2 = A3;

    void setup()
    {
      Serial.begin(19200);
      //Set up relay control pins
      pinMode(Relay1, OUTPUT);
      digitalWrite(Relay1, HIGH);
      // wake up the GSM shield
      SIM900.begin(19200);
      delay(10000);  // give time to log on to network.
      SIM900.print("AT+CMGF=1\r");  // set SMS mode to text
      delay(100);
      SIM900.print("AT+CNMI=2,2,0,0,0\r");
      // output contents of new SMS upon receipt to the GSM shield's serial out
      delay(100);
      Serial.println("Ready...");
      }

    void loop()
    {

      //If a character comes in from the cellular module...
      if(SIM900.available() >0)
      {
        inchar=SIM900.read();
        Serial.println(inchar);
        if (inchar=='#')
        {...}
        SIM900.println("AT+CMGD=1,20"); // delete all SMS
      }
    }

**GSM.h** - in this case I haven't even gotten past the .begin() command. This code is from the example at http://arduino.cc/en/Tutorial/GSMExamplesReceiveSMS

    #include <GSM.h>

    // PIN Number for the SIM
    #define PINNUMBER ""

    // initialize the library instances
    GSM gsmAccess(true);
    GSM_SMS sms;
    GSM3_NetworkStatus_t   gsmStatus;
    // Array to hold the number a SMS is retreived from
    char senderNumber[20];

    void setup()
    {
      // initialize serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

      Serial.println("SMS Messages Receiver");
      char code = 'X';
      Serial.flush();
      gsmStatus = gsmAccess.begin(PINNUMBER,false,false);

      int retrycount = 60;
      while (gsmStatus != GSM_READY && retrycount-- > 0) {
        delay(1000);  // lower delay value could lead to unstable state
        theGSM3ShieldV1ModemCore.manageReceivedData();
        gsmStatus = gsmAccess.getStatus();
      }

      if (gsmStatus != GSM_READY) {
        Serial.println("\n[ERR]: GSM connection failed\n");
        Serial.flush();
        gsmAccess.shutdown();
        delay(250);
        digitalWrite(3,LOW);
      }

      Serial.println(" [DONE]");

      // connection state
      boolean notConnected = true;
      // Start GSM connection
      while (notConnected)
      {
        if (gsmAccess.begin(PINNUMBER) == GSM_READY)
      {
          notConnected = false;
      }
        else
        {
          Serial.println("\nNot connected");
          delay(1000);
        }
      }
      Serial.println("GSM initialized");
      Serial.println("Waiting for messages");
    }

title: Error AT% With GSM/GPRS Shield

Answers: 2

body: Check your baud rates. They appear to be different. That will cause problems.

body:
I used Mega 2560 connected to GSM shield as following:

- GSM TX --- pin 10 on Mega
- GSM RX --- pin 3 on Mega

- GND to GND


body:
Is it possible to simultaneously output a clock signal and it's inverse using the timer register(s)?

I'm using the following code in arduino to output a 1MHz signal on OC1A:

    //Use Timer/Counter1 to generate a 1MHz square wave on Arduino pin 9.
    //J.Christensen 27Apr2012

    void setup(void)
    {
        DDRB = _BV(DDB1);                  //set OC1A/PB1 as output (Arduino pin D9, DIP pin 15)
        TCCR1A = _BV(COM1A0);              //toggle OC1A on compare match
        OCR1A = 7;                         //top value for counter
        TCCR1B = _BV(WGM12) | _BV(CS10);   //CTC mode, prescaler clock/1
    }

    void loop(void)
    {
    }

title: How to program a CLK signal and its inverse with Arduino/AVR

Answers: 4

body:
What about also setting COM1B0 and then setting the initial values of OC1A and OC1B to opposites by writing to PORTB?

Also, I presume you mean 1 MHz and not 1 mHz?

body:
Various AVRs have the capability to output both the normal and inverted timer waveform from a single output compare register simultaneously on two pins. These devices include, but are not limited to, ATtinyX5/V, ATtiny26/L, ATtinyX61A, and ATmegaXXU4.

The ATmega328P does not have this capability, therefore the smallest primary source Arduino that does is the Leonardo (ATmega32U4) and comparable devices. The Adafruit Trinket and the Digispark (both ATtiny85-based) also offer this.

body:
Another option is to do this in hardware - it's trivial to invert a signal.

For example, see the selected answer for https://electronics.stackexchange.com/questions/30238/how-to-invert-a-digital-signal - the second diagram - connect Vs to your clock, and Vo will be your inverted clock. For the two resistors, anything over 1k should be fine. Or use an inverter (which is the same thing, in one component, but is much less likely to be in your random-part box).

Note: There will be a very short delay going through this circuit - one place I saw suggested 1.5ns, but see the spec sheet of your transistor. A 1mhz clock "ticks" at 1,000ns (I guess, 500ns on, 500ns off), so this delay shouldn't be significant.

body:
<!-- language-all: lang-C++ -->

How about this?

    void setup()
      {
      // Defining PB1 and PB2 as outputs by setting PORTB1 and PORTB2
      // Setting DDB1 and DDB2
      DDRB |= bit (DDB1) | bit (DDB2);

      // stop timer 1
      TCCR1A = 0;
      TCCR1B = 0;

      TCCR1A = bit (COM1B0) | bit (COM1B1)  // Set OC1B on Compare Match, clear
                                            // OC1B at BOTTOM (inverting mode)
             | bit (COM1A1)                 // Clear OC1A on Compare Match, set
                                            // OC1A at BOTTOM (non-inverting mode)
             | bit (WGM11);                 // Fast PWM, top at ICR1
      TCCR1B = bit (WGM12)  | bit (WGM13)   //       ditto
             | bit (CS11);                  // Start timer, prescaler of 8

      // Initialize OCR1A = 300 (pulse_width = 150us), OCR1B, and ICR1
      ICR1 = 0xFFFF;
      OCR1B = 299;
      OCR1A = ICR1 - OCR1B;

      }  // end of setup

    void loop()
      {
      }

Results on a Uno:

[![Normal and inverted timer output][1]][1]

Output on Uno pins 9 and 10.

Change the prescalers and counters to your desired frequency.

---

The screenshot doesn't show one signal exactly the inverse of the other. The *pattern* is inverted. If you had a 50% duty cycle, it would be an exact inverse.

---

> It looks good except they overlap (slightly) by 50ns. If I set them to 16 and 8, respectively, they don't overlap but they are slightly asymmetrical

OK, make OCR1A and OCR1B both 7:

      ICR1 = 15;
      OCR1B = 7;
      OCR1A = 7;

*Why 7? And why 15?*

The counts are zero-relative. So by counting to 15 on a 16 MHz processor we are actually getting 1/16th of the clock, namely 1 MHz. And half of that is 8 (which, zero-relative, is 7). So we are really doing:

* Period: 16 ticks of the 16 MHz clock
* Duty cycle: 8 ticks of the 16 MHz clock

---

Now, one cycle:

[![Scope shot 1][2]][2]

They change over at the same instant - pulse width exactly 500 ns.

[![Scope shot 2][3]][3]

And they change back at the same moment - pulse width also 500 ns.

  [1]: https://i.stack.imgur.com/mc8Sk.png
  [2]: https://i.stack.imgur.com/YefHP.png
  [3]: https://i.stack.imgur.com/dNPMd.png


body: When reading the MPU 6050 has accelerometer and gyro, I assumed it was linear acceleration, but now I second guess that.  From this video https://www.youtube.com/watch?v=qmd6CVrlHOM it seems like they are using acceleration and gyro to make one rotation direction.  I need to know what direction the mpu is moving, not just a rotational value.  Is there a way to extract this information?

title: Linear acceleration from MPU 6050

Answers: 2

body:
The MPU6050 has an accelerometer and a rate gyro (which tells you how fast it is rotating). The accelerometer will tell you which direction is down and in a motionless situation, that is all the information you have.

You'll probably want something like the MPU9150, it has a compass, which will give you the directional information you're asking for.

body:
The MPU6050 has accelerometers in the x, y, and z axis. When placed on flat surface with no acceleration, you should get 0g (or whatever unit it uses, I cannot remember off the top of my head) in the x and Y directions, and 1g in the z axis. By continuously polling these values, you can find out the linear  acceleration of each axis at a given moment in time.

What you saw is probably because the chip also has three Gyroscopes, for measuring rotational acceleration and speed. The chip can do both.


body:
I'm trying to run a simple Hello World program from [Arduino 1.6.5][1] from terminal. When I run it in Arduino IDE, it works good. When I'm trying to get it by `avr-g++` I have hard way to figure out how to include all libraries - so far I got this script:

    avr-g++ -Os -DF_CPU=16000000UL -mmcu=atmega328p -c -o main.o main.cpp
    -I"../arduino-1.6.5-r5/libraries/LiquidCrystal/src/"
    -I"../arduino-1.6.5-r5/hardware/arduino/avr/cores/arduino/"
    avr-g++ -mmcu=atmega328p main.o -o main
    avr-objcopy -O ihex -R .eeprom main main.hex
    sudo avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyACM1 -b 115200 -U flash:w:main.hex

First line (with both `-I` flags) compiles, but after running second line, I get:

    main.o: In function `main':
    main.cpp:(.text.startup+0xa): undefined reference to `LiquidCrystal::begin(unsigned char, unsigned char, unsigned char)'
    main.cpp:(.text.startup+0x16): undefined reference to `Print::print(char const*)'
    main.o: In function `_GLOBAL__sub_I_lcd':
    main.cpp:(.text.startup+0x3a): undefined reference to `LiquidCrystal::LiquidCrystal(unsigned char, unsigned char, unsigned char, unsigned char, unsigned char, unsigned char)'
    collect2: error: ld returned 1 exit status

How can I also include some libraries? I need the exact bash script.

  [1]: https://www.arduino.cc/en/Main/Software

title: avr-g++ (or avr-gcc) and LiquidCrystal library

Answers: 1

body:
I made a Makefile to compile the Blink program a little while back. It wasn't trivial.

    #
    # Simple Arduino Makefile
    #
    # Author: Nick Gammon
    # Date: 18th March 2015

    # where you installed the Arduino app
    ARDUINO_DIR = C:/Documents and Settings/Nick/Desktop/arduino-1.0.6/

    # various programs
    CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc"
    CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++"
    AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar"
    OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy"

    MAIN_SKETCH = Blink.cpp

    # compile flags for g++ and gcc

    # may need to change these
    F_CPU = 16000000
    MCU = atmega328p

    # compile flags
    GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106
    CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions
    CC_FLAGS  = $(GENERAL_FLAGS)

    # location of include files
    INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/variants/standard"

    # library sources
    LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/cores/arduino/"

    build:

     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o
     rm core.a
     $(AR) rcs core.a malloc.c.o
     $(AR) rcs core.a realloc.c.o
     $(AR) rcs core.a WInterrupts.c.o
     $(AR) rcs core.a wiring.c.o
     $(AR) rcs core.a wiring_analog.c.o
     $(AR) rcs core.a wiring_digital.c.o
     $(AR) rcs core.a wiring_pulse.c.o
     $(AR) rcs core.a wiring_shift.c.o
     $(AR) rcs core.a CDC.cpp.o
     $(AR) rcs core.a HardwareSerial.cpp.o
     $(AR) rcs core.a HID.cpp.o
     $(AR) rcs core.a IPAddress.cpp.o
     $(AR) rcs core.a main.cpp.o
     $(AR) rcs core.a new.cpp.o
     $(AR) rcs core.a Print.cpp.o
     $(AR) rcs core.a Stream.cpp.o
     $(AR) rcs core.a Tone.cpp.o
     $(AR) rcs core.a USBCore.cpp.o
     $(AR) rcs core.a WMath.cpp.o
     $(AR) rcs core.a WString.cpp.o
     $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm
     $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep
     $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

---

I basically did this by observing what the IDE does (as Ignacio Vazquez-Abrams suggested) and replicated it. Now to add libraries you have to add even more steps.


body:
I'm having a small issue with the CD74HC4067 multiplexer/demultiplexer: I am using it to receive data from an array of sensors (at the moment I have only 2, but in a near future they will grow). Specifically I have a light sensor and a sound sensor.

Mux output is connected to A0 since the readings I do are analog. The pins I use to switch the channels are A3 and A2 (when the other sensors will arrive also A1 will be dedicated to that).

My problem is that when switching between one channel and another, my readings highly fluctuate, but only when the reading value is > 500 or so, and I don't understand why. In a simple sketch I've tried adding some delay (40 msec) and the issue goes away. But in my project which is far more complex and uses also other analog channels I need a delay of ~1 second to get a correct reading, which is absolutely unacceptable since I need it to run in real-time(ish). I also tried using the digital pins to control the mux but to no avail. The only thing that seems to stabilize everything is connecting a capacitor between the MUX out and ground, and using a 20msec delay, but it only works for a bit.

I hope I've been clear enough and that someone can point me the right way!

EDIT:

Here is the schematic
[![Schematic][1]][1]
<!-- source: https://s27.postimg.org/yyb1s82f7/illu_arduino_UNO.png -->

(Error in the drawing: "temp" is actually a "light sensor" as in the bottom of the post...)

And my code:

    #define MUX A0
    #define S0 A2
    #define S1 A3

    void setup() {
      Serial.begin(9600);
      pinMode(S0, OUTPUT);
      pinMode(S1, OUTPUT);

      selectMux(1);
    }

    void loop() {

      //selectMux(0);
      //Serial.println(analogRead(MUX));
      //selectMux(1);
      Serial.println(analogRead(MUX));

    }

    void selectMux(byte port) {
    //  pinMode(MUX, mode);
      int r0 = bitRead(port, 0);
      int r1 = bitRead(port, 1);

      digitalWrite(S0, r0);
      digitalWrite(S1, r1);
      analogRead(MUX);
    }

the `analogRead(MUX)` in the selectMux function was added because I read in a post that they suggested to do that in order to get a more accurate reading.
With this code only the results already fluctuate:

    Output:
    76
    41
    77
    76
    76
    75
    36
    75
    74
    76
    77
    106
    76
    76
    76
    76

but it goes crazy when the input is higher, close to 5V:

    Output:
    948
    780
    340
    948
    948
    635
    437
    949
    948
    499
    551
    949
    950
    396
    684
    950

If you enable the commented code that starts to switch the outputs it is even worse. As I said, adding delays helps, but in my final application I cannot afford to have 1s delays.

I also show that in the circuit there is a timer that uses other Analog pins, but in the code I didn't include that part. If you need I'll add that too.

[Sound Sensor](http://www.dx.com/p/157205),
[Light Sensor](http://www.dx.com/p/152409)

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

title: Issue with CD74HC4067 MUX on high values

Answers: 1

body:
I don't think you should leave s2 and s3 floating. A floating pin does not mean nor 0 nor 1.

Connect them both to ground.


body:
I want to make the vibration motor vibrate depending on the distance to an obstacle, for example if the distance is too short it should vibrate quickly and vice versa.

How can i make motor vibrate using arduino depending on the distance?
Can you explain for me how can I use the delay in the vibration code?
I found this code in the internet for vibration:

    digitalWrite(y, HIGH);
    delay(50);
    digitalWrite(y, LOW);
    delay(50);

I know that I can change the delay, but how can we do it depending on our purpose?
Please help me .. I don't know the use of the delay :(

title: How can I make motor vibrate using arduino depending on the ultrasonic distance?

Answers: 3

body:
You could just replace the "50" in the first delay with the ultrasonic distance variable, I'll explain a bit more below.

Let's assume your ultrasonic sensor outputs an analogue value between 0V and 5V. The output is connected to analog pin A0. Then you just set pinMode(A0, INPUT) and analogRead the value from the pin and store it in the variable X or whatever. Then you just use the variable X as a delay and it will do what you want. The higher the value gets the longer it will vibrate. Something like this:

    [...]
    val = analogRead(A0);
    digitalWrite(5, HIGH);
    delay(val);
    digitalWrite(5, LOW);
    [...]

Second option, if you only wish to turn it on if it is above or under a certain limit, would be using an if condition.

For example:

    if(variable > 50){
      // if the variable named variable is over 50 this code is going to be executed
    } else {
      // If the variable is below 50 this is executed
    }

If you are unfamiliar with if conditions then I suggest reading [this too][1].

  [1]: https://www.arduino.cc/en/Reference/if

body:
I want to show you my thinking, and tell me please if it is right or wrong:

I build an relationship between the distance and the speed.

I know that (speed = distance/time) and if the obstacle is too close to the ultrasonic sensor the speed of the motor should be maximum, so I have decrease the time which is the delay, right?

I make the code according what i said above and it is shown below:

        if(distance <= 60 && distance >= 45)// the distance is too large
        {
        digitalWrite(motorPin, HIGH);

        delay(200);// I increase the delay to make the motor vibrate slowly

        digitalWrite(motorPin, LOW);

        delay(200);

        }

        else if(distance < 45 && distance >= 30)
        {
        digitalWrite(motorPin, HIGH);

        delay(100);

        digitalWrite(motorPin, LOW);

        delay(100);

       }
        else if(distance < 30){

        digitalWrite(motorPin, HIGH);

        delay(50);

        digitalWrite(motorPin, LOW);

        delay(50);

      }
      else
      {
        digitalWrite(motorPin, LOW);// If the distance is too large the motor will be off
      }

body:
> I know that I can change the delay, but how can we do it depending on our purpose?

Are you asking how to use a *variable*? An example:

<!-- language-all: lang-C++ -->

    const int LED = 13;

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

    void loop()
      {
      int amount = analogRead (A0);   // get a reading
      digitalWrite(LED, HIGH);
      delay(amount);
      digitalWrite(LED, LOW);
      delay(amount);
      }

That code reads some analog device, and adjusts the delay based on the figure it read.


body:
I have a device built with an Arduino uno:

- Arduino software installed on an Arduino uno

- can be controlled via serial commands

- can be controlled via physical buttons and sensors

- on any button/sensor state change it writes the current state to serial

- if no message has been sent within 5 seconds, it sends a no-change serial message

---

What is needed:

- Use an ESP8266 to provide a bridge between current Arduino software and MQTT / web

- I can program the ESP8266 as a web server, MQTT client, etc with the Arduino IDE or Lua (but I prefer the Arduino IDE since I can reuse parts of the code to generate / interpret communication).

- the ESP8266 will handle everything that is required for wifi / web / MQTT; without the MQTT module the Arduino part will work stand-alone, only the remote control will be missing.

- I would like to make minimal changes to the Arduino code (or none, if possible). Any changes would involve extensive re-testing, which I try to avoid.

- the ESP8266 can be missing in some installs.

---

What options I found:

1. Serial

ESP8266 can read the serial output and be a bridge between web/MQTT and serial, will store the current state in memory to be sent when requested to avoid polling the device every time.

One of the benefits is no code changes / testing required for the Arduino part.

2. I2C

Make the Arduino the I2C master and the ESP8266 the slave (or the other way around) and implement bi-directional communication. Got the idea by reading [this thread][1].

---

Some other information about the serial commands:

A data packet (command or state description) consists of 1 to 20 characters, with a possible peak of 20 packets in 5 seconds, and an average of one packet every 3 seconds. If needed, I can make this send 5 unsigned integers instead of alphanumeric characters.

If more than the I2C / serial pins are needed I can upgrade to an Arduino Mega (so the number of free pins is not an issue).

Are there any other options for this? (protocols, pre-made libraries for serial communication, etc). I'm trying not to reinvent the wheel..

Thank you for your time!

  [1]: https://arduino.stackexchange.com/questions/3042/i2c-2-way-communication-between-arduino-uno-and-arduino-mega

title: Protocol options for data exchange between Arduino and ESP8266

Answers: 2

body:
Most I2C tutorials made each Arduino a slave and master, but [this][1] approach is better, because each Arduino is either a master or a slave (not both) and no switching is needed. That makes things easier.

I2C is better than serial, because you can add more Arduinos in the same bus.

I have implemented I2C between two Arduinos and it's not more complicated that reading/writing to the serial port (which you have already done). And I bet you can generalize your serial port code to work with both serial and I2C comms.

This is my example (just a proof of concept). The slave Arduino controls a some pins, a temp. sensor and a watchdog under orders from the master Arduino. If slave doesn't receive a beat in time, it reset the master Arduino.

**Master code**

    #include <Wire.h>

    #define CMD_SENSOR    1
    #define CMD_PIN_ON    2
    #define CMD_PIN_OFF   3
    #define CMD_LUMEN     4
    #define CMD_BEAT      5

    const byte SLAVE_ADDRESS = 42;
    const byte LED = 13;

    char buffer[32];

    void setup ()
    {
      Serial.begin(9600);
      Serial.println("Master");

      Wire.begin ();

      pinMode (LED, OUTPUT);
      digitalWrite(LED, HIGH);
      delay(1000);
      digitalWrite(LED, LOW);

      Wire.beginTransmission (SLAVE_ADDRESS);
      Serial.println("Send LED on");
      Wire.write (CMD_PIN_ON);
      Wire.write (2);
      Wire.write (10);
      Wire.endTransmission();
      int x = Wire.requestFrom(SLAVE_ADDRESS, 1);
      Serial.print("status=");
      Serial.println(x);
    }  // end of setup

    void loop ()
    {
      Serial.println(".");
      Wire.beginTransmission (SLAVE_ADDRESS);
      Wire.write (CMD_SENSOR);
      Wire.endTransmission();
      int x = Wire.requestFrom(SLAVE_ADDRESS, 1);
      Serial.print("Disponibles = ");
      Serial.println(x);
      int temp = (int) Wire.read();
      Serial.println(temp);

      Wire.beginTransmission (SLAVE_ADDRESS);
      Wire.write (CMD_LUMEN);
      Wire.endTransmission();
      Wire.requestFrom(SLAVE_ADDRESS, 2);
      int light = Wire.read() << 8 | Wire.read();
      Serial.print("Light=");
      Serial.println(light);

      Wire.beginTransmission (SLAVE_ADDRESS);
      Wire.write (CMD_BEAT);
      Wire.endTransmission();
      Wire.requestFrom(SLAVE_ADDRESS, 1);

      delay (5000);
    }  // end of loop

**Slave code**

    /*
       Esclavo I2C

       Recibe los siguientes comandos
       <- 1° byte -> <- 2° byte -> <- 3° byte ->
       CMD_SENSOR
       CMD_PIN_ON    n° de pin     duracion en segundos
       CMD_PIN_OFF   n° de pin
       CMD_LUMEN
       CMD_BEAT

       Cada comando recibe una respuesta, ya sea el valor pedido
       o un status.
    */
    #include <max6675.h>
    #include <Wire.h>

    typedef struct {
      int pin;
      unsigned long off;
    } PIN_PGMA;

    /*
       Lista de pines que se pueden activar via CMD_PIN_ON.
    */
    #define PIN_LUMEN   A0
    #define PIN_LED      2
    #define PIN_RESET    3
    PIN_PGMA pgma[] = {
      {PIN_LED, 0},
      {PIN_RESET, 0}
    };
    const int pgmaSize = sizeof(pgma) / sizeof(PIN_PGMA);

    #define CMD_SENSOR    1
    #define CMD_PIN_ON    2
    #define CMD_PIN_OFF   3
    #define CMD_LUMEN     4
    #define CMD_BEAT      5

    #define ST_OK         0
    #define ST_BAD_PIN    1
    #define ST_TIME_0     2
    #define ST_BAD_LEN    3

    #define MY_ADDRESS  42

    //  Maximo tiempo de espera entre comandos CMD_BEAT. Pasado
    //  ese tiempo, se activa el PIN_RESET.
    //  En milisegundos.
    #define BEAT_INTERVAL 10000
    unsigned long lastBeat;
    //  Largo del reset en milisegundos.
    #define RESET_LENGTH  250
    byte cmd = 0;
    byte status = 0;

    int thermoDO = 11;
    int thermoCS = 12;
    int thermoCLK = 13;

    MAX6675 thermocouple(thermoCLK, thermoCS, thermoDO);

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

      pinMode(PIN_LUMEN, INPUT);
      analogRead(PIN_LUMEN);

      for (int i = 0; i < pgmaSize; i++) {
        pinMode(pgma[i].pin, OUTPUT);
        digitalWrite(pgma[i].pin, LOW);
      }
      lastBeat = millis();

      Wire.begin (MY_ADDRESS);
      Wire.onReceive (receiveCommand);
      Wire.onRequest (sendAnswer);
    }

    void loop()
    {
      unsigned long now = millis();

      //  Baja la linea de RESET si no ha recibido un beat ultimamente.
      unsigned long diff = now - lastBeat;
      if (diff > BEAT_INTERVAL) {
        resetPin();
      }

      //  Recorre la lista de pines y apaga aquellos cuyo tiempo termino.
      for (int i = 0; i < pgmaSize; i++) {
        if (pgma[i].off > 0 && pgma[i].off <= now) {
          Serial.print("off pin="); Serial.println(pgma[i].pin);
          pgma[i].off = 0;
          digitalWrite(pgma[i].pin, LOW);
        }
      }
    }

    // called by interrupt service routine when outgoing data is requested
    void sendAnswer() {
      byte temp;
      int  lightReading;

      switch (cmd) {
        case CMD_SENSOR:
          temp = thermocouple.readCelsius();
          Wire.write(temp);
          break;
        case CMD_LUMEN:
          lightReading  = analogRead(PIN_LUMEN);
          Wire.write(lightReading >> 8);
          Wire.write(lightReading % 0xFF);
          break;
        case CMD_PIN_ON:
        case CMD_PIN_OFF:
        case CMD_BEAT:
          Wire.write(status);
          status = ST_OK;
          break;
      }
      cmd = 0;
    }

    // called by interrupt service routine when incoming data arrives
    void receiveCommand (int howMany) {
      cmd = Wire.read ();
      status = ST_OK;
      switch (cmd) {
        case CMD_PIN_ON:
          cmdPinOn();;
          break;
        case CMD_PIN_OFF:
          cmdPinOff();
          break;
        case CMD_BEAT:
          lastBeat = millis();
          break;
      }
    }  // end of receiveEvent

    void cmdPinOff() {
      if (Wire.available() != 1) {
        status = ST_BAD_LEN;
      } else {
        int pin = Wire.read();
        int i = searchPin(pin);
        if (i < 0) {
          status = ST_BAD_PIN;
        }
        else {
          pgma[i].off = 0;
          digitalWrite(pin, LOW);
        }
      }
    }

    int searchPin(int pin) {
      int i = pgmaSize - 1;
      while (i >= 0 && pgma[i].pin != pin) {
        i--;
      }
      return i;
    }

    /*
     * Programa el encendido y duracion del RESET.
     */
    void resetPin() {
      if (digitalRead(PIN_RESET) == LOW) {
        unsigned long now = millis();

        int i = searchPin(PIN_RESET);

        pgma[i].off = now + RESET_LENGTH;
        lastBeat = now;
        digitalWrite(PIN_RESET, HIGH);
      }
    }

    void cmdPinOn() {
      if (Wire.available() != 2) {
        status = ST_BAD_LEN;
      } else {
        int pin = Wire.read();
        int len = Wire.read();

        int i = searchPin(pin);
        Serial.print("pin="); Serial.print(pin); Serial.print(",index="); Serial.println(i);
        if (i < 0) {
          status = ST_BAD_PIN;
          Serial.println("bad pin");
        } else {
          if (len == 0) {
            status = ST_TIME_0;
            Serial.println("ban len");
          }
          else {
            pgma[i].off = millis() + len * 1000;
            digitalWrite(pin, HIGH);
            Serial.println("ok");
          }
        }
      }
    }

  [1]: http://www.berryjam.eu/2014/07/advanced-arduino-i2c-communication/

body:
Using I2C (which i recommend over serial), you may not use a NodeMCU ESP8266 as a slave.  It can only function as master.  An Arduino, on the other hand, may be either.  Therefore, the Arduino will always be passive and the NodeMCU will be the master.

What you can do, is implement a semaphore ([as described by Majenko here][1]), where the Arduino signals that it has something to "say" to the master, causing the master to request from the Arduino.  It could, under these circumstances, be labeled an "obliging master" (neologism).

NEVER print to serial from inside `requestEvent` or `receiveEvent`.

  [1]: https://arduino.stackexchange.com/a/67462/30341


body:
I am looking for something like a **multiway "relay dimmer"**.
Which lets me dim a light using an Arduino and a manual dimmer.
[![Schematic][1]][1]

(The manual dimmer should work without any computer!)

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

title: Multiway Relay Dimmer

Answers: 2

body:
You could use a rotary encoder for that purpose!

Basically the rotary encoder is a knob that, for every "tick" you give it, it returns a different value to your Arduino. With a bit of programming you can sense the direction of the turn, if it is positive then you lighten up the LED, and vice versa.

I used that to control a RGB led, it works very well! [here](http://playground.arduino.cc/Main/RotaryEncoders) some more information on the rotary encoder and the code needed to use it.

body:
I add another answer because I think I found something. After a few days searching on various sites that sell arduino stuff I found this http://www.dx.com/p/8-channel-5v-relay-module-extension-board-for-arduino-avr-arm-51-140703 that might be what you're looking for. One of the customers in the review states it can be used even without Arduino.

I know it's a relay, not a dimmer, but maybe you could add something to your circuit...


body:
I'm planning use Roboteq motor driver for 24V brushed DC motor but I can't be sure that it's true or wrong. You know, Roboteq controller is too expensive and I don't want to spend money in vain. Have you any experience this controller? Are they compatible with Arduino?

http://www.roboteq.com/index.php/roboteq-products-and-services/brushed-dc-motor-controllers/mdc2230-detail  Roboteq Controller Link

I also think, Pololu RoboClaw driver. https://www.pololu.com/product/1499 I don't know is it enough for wheelchair. Because, I already have used Pololu VNH5019 and it is not enough. (synchronicity and noise problems etc.)

If you have any ideas, I will be glad. Thank you.

title: Is Roboteq motor driver compatible with Arduino?

Answers: 1

body: It is not directly supported. But the device description lists RS232 port that can be interfaced with an Arduino using a TTL to RS232 converter. The description also mentions "several Analog, Pulse and Digital I/Os which can be remapped as command or feedback inputs, limit switches, or many other functions" so it is totally possible to control the controller with an Arduino, but depending on the method you choose it may require some effort.


body:
I am trying to get a reading from my Cotek through my Arduino and have it display on an LCD screen. When I run the code, though, nothing shows up. I am EXTREMELY new to using pretty much all this equipment so honestly, I have little to no idea what I'm doing. I am not sure if it is a wiring issue, an issue with the code or both. Any and all help is appreciated.

This is how the cotek is wired to the Arduino. The middle red wire (in the middle of the two resistors) is connected to AUX from the cotek. The two outer red wires are connected to the SDA and SCL of the cotek and their corresponding blue wires are connected to the SDA and SCL of the Arduino (the two resistors are 2KOhm pull-up resistors). The blue wire on the bottom is connected to the GRND of the cotek which is also connected to GRND of the Arduino.
![connection from cotek to arduino](https://i.stack.imgur.com/IfYBp.jpg)

This is my code using the I2C protocol:
<!-- language-all: lang-cpp -->

    #include <LiquidCrystal.h>
    #include <Wire.h>

    int analogPin = 5;
    char address= 0;
    int numBytes = 2;
    char val = 0;
    int debug = 5;
    LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 2);

    void setup() {
      // put your setup code here, to run once:
      Wire.begin();
      Serial.begin(9600);
      lcd.begin(16, 2);
      lcd.clear();
    }

    void loop() {
      // put your main code here, to run repeatedly:
      Wire.requestFrom(address, numBytes);
      while(Wire.available())
      {
        val = Wire.read();
        Serial.print(val);
        lcd.setCursor(0,0);
        lcd.print(val);
      }
      //perform function to change val from hexadecimal to decimal number here
      delay(500);

I am pretty sure the LCD is wired correctly to the Arduino as I was able to communicate to it previously without using the Cotek. In any case, it doesn't matter as 'val' doesn't even appear on the serial monitor.

Again, any help would be appreciated. Thanks!

title: Basic communication between Cotek and Arduino UNO

Answers: 0


body:
I'm in the echopen association, our goal is to create a low cost, open source echographic probe. In order to do that, we use an arduino due for the first step. For doing acoustic imaging, we use ultrasonic transducer wich works at high frequency, typically 5 MHz. So, for our purpose we need to send and receive analogic signal at high frequencies.
We want to connect a 80 Msps DAC and a 80 Msps ADC to the arduino due so we can generate and mesure analog signal up to 42 MHz. I have found here (http://www.instructables.com/id/Arduino-Timer-Interrupts/#step0) how to use arduino timer interrupts in order to send and receive data at 84 MHz. I haven't connect my converters for the moment, but I have preliminary questions.
First, is the definition of the timer is the same for the arduino due (i.e. timer1 is a 16 bits timer) ? Morever, my ADC and DAC are 14 bits converters, can I tell to the arduino to sent only 14 bits digital signal ?
Secondly, as we work at high frequencies we will have to send a lot of data from the microcontroller to a computer via the serial port. I have make a test and at 250000 bauds it takes nearly 0.5 second to transfer 4300*8 bits datas. It is to slow for our purpose, how can I do it faster ?

title: Connecting high sampling rate DAC and ADC to arduino DUE, timer consideration

Answers: 3

body:
I'm sorry, but by your description you are doomed to failure from the start.

The Arduino Due runs at 84MHz.  That doesn't mean that it can communicate at 84MHz, only that it can process its instructions at around 84 million per second.

In order for you to transmit or receive 80 million samples per second you have to be able to a) transmit sample words (14 bits) 80 million times per second, and b) process the information between each sample.

That means you are going to require a processor that operates considerably faster than 84MHz.

For instance, assuming you are using high speed synchronous serial communication (say, SPI) to transfer the data.  For 16 bits of data (you won't get it to do just 14 bits using hardware and software would be way too slow) would require a transmission clock of (80000000 * 16) 1.28GHz.

If you're using a 16-bit parallel interface then you would only need an 80MHz communication clock to move the data around, but receiving that data and storing it somewhere and also processing it would require many many more instructions between each clock.  Far more than the Due could perform.  Certainly it's way way outside the scope of a timer interrupt.

I would suggest instead investigating systems that run in the high hundreds of Megahertz or even Gigahertz range.  Maybe one of the newer "version 2" Raspberry Pi embedded computers may be suitable.

body:
If I'm interpreting the datasheet correctly, you might be able to use the Static Memory Controller (SMC) capability of the Cortex M3 Sam3X to attach some 128K x 8 SRAM devices to your Due.  If your ADC and DAC support tri-state outputs then they could be attached the same way as memories (but ignoring address lines as irrelevant), allowing memory-to-memory DMA transfers.  Ie one could either input and store batches of ADC results at 42 MSPS, or could output batches of data to DAC at 42 MSPS, or could do simultaneous I/O at 21 MSPS.  I haven't read the DMA section closely enough to verify that this will work with the M3.

See Figure 25-2 in Section 25.6.2 of the datasheet regarding memory controllers, and Section 26, “Peripheral DMA Controller (PDC)”, regarding DMA.  Also see the eevblog.com page, “[Looking for Cortex M3 or M4 with DMA to GPIO capability](http://www.eevblog.com/forum/microcontrollers/looking-for-cortex-m3-or-m4-with-dma-to-gpio-capability/)”.

body:
May I suggest you decorrelate the acoustic frequency with the sampling frequency ?

While you need the high frequencies to get spatial resolution, what you are interested in is only the signal return amplitude (not the exact waveform), which you could sample at a much lower rate using appropriate analog front end.


body:
I have this simple code who send a signal to a android phone when I press a button:

<!-- language-all: lang-C++ -->

    const int botonPinD = 8;
    const int relayPin =  12;
    int retardo = 100;
    int finBoton=1000;

    void setup() {
      pinMode(relayPin, OUTPUT);

      pinMode(botonPinA, INPUT);
      pinMode(botonPinB, INPUT);
      pinMode(botonPinC, INPUT);
      pinMode(botonPinD, INPUT);
    }
    void loop(){
        botonD = digitalRead(botonPinD);
        if (botonD == HIGH){
       // for simplicity remove botonA, botonB and botonC code, but it's the same with a few digitalWrite
            digitalWrite(relayPin, HIGH);
            delay(retardo);
            digitalWrite(relayPin, LOW);
            delay(retardo);
            digitalWrite(relayPin, HIGH);
            delay(retardo);
            digitalWrite(relayPin, LOW);
            delay(retardo);
            digitalWrite(relayPin, HIGH);
            delay(retardo);
            digitalWrite(relayPin, LOW);
            delay(retardo);
            digitalWrite(relayPin, HIGH);
            delay(retardo);
            digitalWrite(relayPin, LOW);
            delay(retardo);
            delay(finBoton);
          }
          else{
            digitalWrite(relayPin, LOW);
          }
    }

But if I press the button fast (maybe a half a second between clicks) I only receive once the signal.

I'm not very sure about what's happened here (I'm an Arduino newbie). The first signal, has it locked the channel? Can signals be queued? Can I control the way that they are queued?

title: digitalWrite queued signals?

Answers: 2

body:
The main problem I guess you are suffering from is the good old `delay()` blockage.

`delay()` is a terrible function and should be avoided at all costs.  Nothing at all can happen while you are running `delay()` - that means you can't be reading the state of your button - until all your `delay()` calls have finished.

If you want to queue the pressed of the button you will need to do three things:

1. You will need to recognise when the button changes from LOW to HIGH, not just "when it is HIGH" as you do now.
2. You will have to queue that button press somewhere. The simplest way is to maintain a count of how many times the button has been pressed.
3. You will have to process any pending button presses ("while the count > 0") by triggering your output with the right timing without using `delay()`, which means using `millis()` and maintaining state information.

body:
The code below is closer to what you seem to be asking about:

<!-- language-all: lang-C++ -->

    // For Mega2560

    const int BUTTONS = 4;
    const int FIRST_SWITCH = 18;
    const int FIRST_RELAY =  41;
    const int CLICKS = 5;
    const unsigned long DEBOUNCE_TIME = 20;  // ms

    int retardo  = 300;
    int finBoton = 1000;

    volatile byte counts [BUTTONS];
    unsigned long lastPress [BUTTONS];

    void doInterrupts (const int which)
     {
     // debounce
     if (millis () - lastPress [which] < DEBOUNCE_TIME)
       return;

     lastPress [which] = millis ();
     counts [which]++;
     }  // end of doInterrupts

    void pin18Pressed ()
      {
      doInterrupts (0);
      }  // end of pin18Pressed

    void pin19Pressed ()
      {
      doInterrupts (1);
      }  // end of pin19Pressed

    void pin20Pressed ()
      {
      doInterrupts (2);
      }  // end of pin20Pressed

    void pin21Pressed ()
      {
      doInterrupts (3);
      }  // end of pin21Pressed

    void setup()
      {
      // configure inputs / outputs
      for (int i = 0; i < BUTTONS; i++)
        {
        pinMode (FIRST_SWITCH + i, INPUT_PULLUP);
        pinMode (FIRST_RELAY + i, OUTPUT);
        }

      attachInterrupt (5, pin18Pressed, FALLING);
      attachInterrupt (4, pin19Pressed, FALLING);
      attachInterrupt (3, pin20Pressed, FALLING);
      attachInterrupt (2, pin21Pressed, FALLING);

      } // end of setup

    // turn relay on for a particular switch
    void handleSwitchPress (const int which)
      {
      for (int i = 0; i < CLICKS; i++)
      {
        digitalWrite(FIRST_RELAY + which, HIGH);
        delay(retardo);
        digitalWrite(FIRST_RELAY + which, LOW);
        delay(retardo);
      }
      delay(finBoton);
      } // end of handleSwitchPress

    // main loop
    void loop()
      {
     for (int i = 0; i < BUTTONS; i++)
       if (counts [i] > 0)
         {
         handleSwitchPress (i);
         counts [i]--;
         }
      }  // end of loop

---

I'll explain parts of it from above:

### Interrupts

To queue up switch presses we can use an interrupt. The Mega has quite a few external interrupts (See: [attachInterrupt()](https://www.arduino.cc/en/Reference/AttachInterrupt)) so I'll use those. You can read about interrupts on [my page about interrupts](http:/www.gammon.com.au/interrupts).

This code attaches four interrupts handlers:

      attachInterrupt (5, pin18Pressed, FALLING);
      attachInterrupt (4, pin19Pressed, FALLING);
      attachInterrupt (3, pin20Pressed, FALLING);
      attachInterrupt (2, pin21Pressed, FALLING);

Because of the way the hardware works we have to use pins 18, 19, 20 and 21 (there are a couple more but these are in sequence).

I set the switches to be INPUT_PULLUP so that they are normally HIGH when not pressed, and go LOW when you press them. Hence the interrupts are looking for a FALLING edge.

---

### Handle one interrupt

An interrupt handler is like this:

    void pin18Pressed ()
      {
      doInterrupts (0);
      }  // end of pin18Pressed

Since they all do much the same thing I put all of the switch management into one function and used an array of switches, like this:

    volatile byte counts [BUTTONS];
    unsigned long lastPress [BUTTONS];

    void doInterrupts (const int which)
     {
     // debounce
     if (millis () - lastPress [which] < DEBOUNCE_TIME)
       return;

     lastPress [which] = millis ();
     counts [which]++;
     }  // end of doInterrupts

In order to "queue" presses the interrupt handler adds one to a counter, for that array item. (So, pin 18 is position 0, pin 19 is position 1 and so on).

---

### Debouncing

Debouncing of the switches is done by ignoring multiple presses in quick succession:

     // debounce
     if (millis () - lastPress [which] < DEBOUNCE_TIME)
       return;

     lastPress [which] = millis ();

---

### Handling a queued press

Now in the main loop we just check if the counter has gone up, for each switch:

     for (int i = 0; i < BUTTONS; i++)
       if (counts [i] > 0)
         {
         handleSwitchPress (i);
         counts [i]--;
         }

If so, we call `handleSwitchPress` which toggles the relay for the desired number of times.

---

### Code for Uno

If you are using a Uno instead of a Mega2560 you don't have four external interrupts. The alternative version below uses *pin change interrupts* instead of external interrupts.

Pin change interrupts work on all pins of the Uno, however they are in batches of three: Pins A0 to A5, pins D0 to D7 and pins D8 to D13. In the code below I use pins 2, 3, 4 and 5 which are in the batch D0 to D7.

With a pin-change interrupt you only get notification of a *change* to the pin, so the code has to detect whether the pin changed from high to low or low to high.

    // For Atmega328 (eg. Uno)

    const int BUTTONS = 4;
    const int FIRST_BUTTON = 2;
    const int FIRST_RELAY =  8;
    const int CLICKS = 5;
    const unsigned long DEBOUNCE_TIME = 20;  // ms

    int retardo  = 300;
    int finBoton = 1000;

    volatile bool oldState [BUTTONS];
    volatile byte counts [BUTTONS];
    unsigned long lastPress;

    // handle pin change interrupt for D0 to D7 here
    ISR (PCINT2_vect)
     {

     // debounce
     if (millis () - lastPress < DEBOUNCE_TIME)
       return;

     lastPress = millis ();

     // check each switch
     for (int i = 0; i < BUTTONS; i++)
       {
       byte state = digitalRead (FIRST_BUTTON + i);
       if (state != oldState [i])
         {
         oldState [i] = state;  // detect state changes
         if (state == LOW)
           counts [i]++;
         }   // end of state change
       }  // end of for each button

     }  // end of PCINT2_vect

    void setup()
      {

      // configure inputs / outputs
      for (int i = 0; i < BUTTONS; i++)
        {
        pinMode (FIRST_BUTTON + i, INPUT_PULLUP);
        oldState [i] = HIGH;
        pinMode (FIRST_RELAY + i, OUTPUT);
        }

      // pin change interrupt (example for D9)
      PCMSK2 |= bit (PCINT18) | bit (PCINT19) | bit (PCINT20) | bit (PCINT21);  // want pins 2, 3, 4, 5
      PCIFR  |= bit (PCIF2);   // clear any outstanding interrupts
      PCICR  |= bit (PCIE2);   // enable pin change interrupts for D0 to D7
      } // end of setup

    // turn relay on for a particular switch
    void handleSwitchPress (const int which)
      {
      for (int i = 0; i < CLICKS; i++)
      {
        digitalWrite(FIRST_RELAY + which, HIGH);
        delay(retardo);
        digitalWrite(FIRST_RELAY + which, LOW);
        delay(retardo);
      }
      delay(finBoton);
      } // end of handleSwitchPress

    // main loop
    void loop()
      {
     for (int i = 0; i < BUTTONS; i++)
       if (counts [i] > 0)
         {
         handleSwitchPress (i);
         counts [i]--;
         }
      }  // end of loop


body:
I was wondering if its possible to send code to the Arduino, and then have it execute this code.

What I'm trying to do is use an Arduino Mega with a bunch of stuff connected to it send code to an Uno with a TFT LCD display to do whatever the Mega tells it to do with the Adafruit GFX Library.  I want to add things to this 'system' gradually so I want the whole program hosted on the Arduino Mega, and a minimal amount of code on the Uno.

Sorry I'm really new at this so if its not possible at all let me know!
Thanks in advance,

-Will

title: Execute Code sent over Serial

Answers: 1

body:
No, it's not possible as you describe it.

The Arduino's main chip, the ATMega328p, is what is known as *Harvard Architecture*.  This means that the Flash memory and RAM both occupy completely separate memory address spaces.  The CPU in the chip is only able to fetch its instructions from the memory space the Flash is connected to (the *Instruction Bus*) and not the memory space the RAM is connected to (the *Data Bus*).  This means it can only run instructions that are in Flash and not RAM.

It is possible to re-program the flash on the fly - after all, that's what the bootloader does, and while the actual act of reprogramming flash is fairly trivial, generating the instructions in the right way is far from trivial.

There are other options though.

1. Use an interpreted language.  I believe there are versions of BASIC available for the Arduino that would allow you to upload a program through the serial port and execute it.
2. Define a protocol (or use an existing protocol) to send pre-defined control commands to the Uno.  Firmata might be of use here.


body:
I am currently building a self balancing robot using an L298N motors driver,and MPU6050 using an arduino microcontroller.

I managed to control my motors movements with no issues. After I extracted the data from my MPU6050 which was easy by using MPU6050 library I faced a problem: When linking the motors movement according to MPU6050 readings, the sensor freezes and stops showing its data on the serial monitor after giving couple of readings, the motors keep moving. I even have capacitors soldered into my motors to filter the noise. I am definitely sure my sensor works perfectly because it was tested before implemented into the motors drivers circuit and code.

If anyone can give me any hints why does the MPU sensor stop giving readings please.

Thanks.

title: Student Project Inquiry(Building a Self Balancing robot)

Answers: 2

body:
The MPU6050 is an I2C device.  By default the Arduino uses the internal pullup resistors in the IO pins for the pullups on the I2C bus.

This is bad - it makes the I2C bus *very* susceptible to noise, and motors are *very* noisy devices.

You need to make sure you have appropriate pullup resistors on the I2C bus (3.3KΩ is good) and keep the I2C wires as short as you reasonably can.

Also keeping power sources as separate as possible is essential.  Don't be tempted to use the 5V power from the Arduino to power your motors - you must use an external power source, or the motors will cause havoc with the microcontroller circuitry and communications.

body:
This answer addresses the additional questions in Salah's comment:
>I am using a 12V battery to power my motors and the ground of the battery is linked to the ground of my motor driver then mounted onto the arduino. So you mean i must use 3.3K resistors and connect them to the SDA and SCL pins on the MPU6050??to prevent any oscillations affecting the sensor is that right ?

The MPU-6050 will work ok with Vdd = 3.3 V.  More specifically, page 14 of the 1788002.pdf datasheet for MPU-6000/MPU-6050 products shows
>VDD = 2.375V-3.46V, VLOGIC (MPU-6050 only) = 1.8V±5% or VDD, TA = 25°C

The wiring diagram on page 39 shows SDA and SCL being pulled up to VLOGIC (which is either 1.8 V or VDD, say 3.3 V).

One suitable choice would be to operate an 8 MHz Mega and the 6050 at 3.3 V and pull SDA and SCL up to 3.3 V via 3.3 KΩ resistors.

Another choice would be to operate a 16 MHz Mega at 5 V, operate the 6050 at 3.3 V, pull SDA and SCL up to 3.3 V via 3.3 KΩ resistors, and use 3.3V/5V level translations on SDA and SCL into the Mega.

Built-in pullups for I/O pins on Mega2560 and similar devices are spec'd at 20 KΩ min, 50 KΩ max, so will provide less restoring current when a device releases a pin, than will a 3.3 KΩ resistor, and thus may be less noise-resistant or operate less speedily.

The important issues for your power wiring are these:

1, Isolate the motor drive and logic drives.  They can use the same ground point but motor current should not be running through the ground lead or leads that connect to the Arduino and the MPU-6050.  And use [decoupling capacitors](https://en.wikipedia.org/wiki/Decoupling_capacitor) as necessary.

2, Power the MPU-6050 with 3.3 V or less; pull up SDA and SCL to that level via 3.3 KΩ resistors; use level translators if the Mega operates at a different voltage than the MPU-6050.

*Edit: About Grounding –* For a detailed discussion, see [Staying Well Grounded](http://www.analog.com/library/analogDialogue/archives/46-06/staying_well_grounded.html), an analog.com article.  For overviews, see [Star Grounding](http://web.archive.org/web/20141030161947/http://www.lh-electric.net/tutorials/gnd_loop.html) at lh-electric.net, or at wikipedia, [Ground Noise](https://en.wikipedia.org/wiki/Ground_noise), [Ground Bounce](https://en.wikipedia.org/wiki/Ground_bounce), and [Ground (electricity) Electronics](https://en.wikipedia.org/wiki/Ground_(electricity)#Electronics).  By “motor current should not be running through the ground lead or leads that connect to the Arduino and the MPU-6050” I refer to the use of separate wires for conducting ground current.  Typically, this will matter only if your motor current is high or noisy.  The idea is to have a heavy wire from the ground post of the battery to the motors, and a separate wire from the ground post of the battery to the Arduino and the MPU-6050.  Voltage across a wire changes as current in the wire changes.  Using separate ground wires, the Arduino and the MPU-6050 are less affected by ground wire voltage changes caused by motor current.


body:
I am working on project and using Arduino Pro Mini (Atmega328p running on 2xAA) to measure the time to charge a capacitor (when the volt level is high). This is the code I used while testing:

    int counter = 0;

    // Charge the capacitor
    digitalWrite(8,HIGH);

    while (digitalRead(7) == LOW) {
        counter = counter +1;
        if (counter > 250) {
            break; // CHARGING FAILED!
        }
    }
The code was working fine when the board was running at 16MHz since the loop was fast enough to give good result. ( counter =~ 28 when the test cap is charged).

However, the intention is to run the system on a battery with clock of 1MHz (to reduce power consumption) and when tested at that speed the counter only reaches 2~3 because the loop it too slow now that the cap will charge in about two to three cycles.

So I did two changes which are using byte instead of int for the counter, and reading the value of the pin directly from the PIND register:

    byte counter = 0;

    // Charge the capacitor
    digitalWrite(8,HIGH);

    while ((PIND & (1<<PD7)) == 0) {
        counter = counter +1;
        if (counter > 250) {
            break; // CHARGING FAILED!
        }
    }
Both of these changes increased the speed and now counter reads ~20 which is much better and almost close to the 16MHz.

Is there any further optimizations?

Can I use one of the general registers instead of the counter, if yes then how? and will that improve the speed?

Is there a more clever and faster way to do this loop?

-----------------------
* Update:

I am going to follow the suggested answer and use the analog comparator, but I also wanted to add to my finding which might help others with general optimization.

Instead of incrementing the counter and comparing if it is larger than some value, it is faster to decrements and compare if it is equal to zero. The counter improved to ~23.

title: Optimizing an Arduino code

Answers: 2

body:
Get rid of the loop altogether. Instead of twiddling and checking bits manually, use timer 1 to trigger the output and capture the input.

If you perform the output on pin 10 and the input on pin 8 then you can use timer 1's output compare to send the pulse out and its input capture to detect when the capacitor has charged.

Untested:

    #include <avr/interrupt.h>

    void setup(void)
    {
      cli();
      DDRB |= _BV(PB2); // Configure OC1B as output
      TCCR1B &= ~(_BV(CS12) | _BV(CS11) | _BV(CS10)); // Stop timer 1
      TCNT1 = 0; // Initialize timer count
      OCR1A = 0xffff; // Reset the timer at this count
      OCR1B = 0xf000; // Upper limit of the timed value, plenty of time before timer reset
      ICR1 = 0xff00; // Set to an invalid initial value
      TCCR1A = _BV(COM1B1); // Trigger output at 0, clear at upper limit
      TCCR1B = _BV(ICES1); // Capture on leading edge
      TCCR1B |= _BV(WGM13) | _BV(WGM12); // High bits for 16-bit fast PWM
      TCCR1A |= _BV(WGM11) | _BV(WGM10); // Low bits for 16-bit fast PWM
      TIMSK = _BV(ICIE1) | _BV(OCIE1B); // Enable input capture and limit interrupts
      sei();
      TCCR1B |= _BV(CS10); // Start the timer at its highest clock speed
    }

    ISR(TIMER1_CAPT_vect)
    {
      TIMSK &= ~(_BV(ICIE1) | _BV(OCIE1B)); // Disable input and limit interrupts
      TCCR1B &= ~(_BV(CS12) | _BV(CS11) | _BV(CS10)); // Stop the timer
      PORTB &= ~_BV(PB2); // Kill the charging output
      // Check ICR1 for the captured value
    }

    ISR(TIMER1_COMPB_vect)
    {
      if (ICR1 == 0xff00)
      {
        // WELL CRAP, charging is taking too long
        // Maybe try with a slower clock?
      }
    }

    void loop()
    {
      // Do other stuff
    }

body:
<!-- language-all: lang-C++ -->

It looks like Ignacio Vazquez-Abrams and I have been doing similar things. :)

I have a page about making a capacitor tester:

[Turn your Arduino into a capacitor tester](http://www.gammon.com.au/forum/?id=12075)

However since link-only replies are frowned on (the link might go down) I'll summarize it here.

The simple approach is to charge the capacitor until it reaches 63.2% of the charging voltage.

That is because:

    1 - e^(-1) = 0.63212

See [RC Time constant - Wikipedia](http://en.wikipedia.org/wiki/RC_time_constant).

We can use the Analog Comparator to trigger an interrupt when the voltage reaches that level.

We need the capacitor to be on pin D6 on the Uno and a reference voltage on pin D7.

See [Using the Arduino Analog Comparator](http://www.gammon.com.au/forum/?id=11916) for more details about the Analog Comparator.

This is much faster than using analogRead, because it triggers on an exact voltage.

Your basic objective is to find how long it takes to reach 63.2% of the supplied voltage (in the example being 1 volt):

[![Capacitor tester 1][1]][1]

In this particular example it took 47 µs for a 47 nF capacitor:

[![Capacitor tester 2][2]][2]

Instead of using an exact reference voltage (ie. 63.2% of 5 volts) you can do some fancy maths instead. Here is my test circuit:

[![Capacitor test circuit][3]][3]

*DUT = Device Under Test*

We plug the values of the resistors into the code like this:

    const float Rc = 10000;    // charging resistor
    const float R1 = 1000;     // between ground and D7
    const float R2 = 1800;     // between +5V and D7
    const float clockRate_us = 16;  // 16 MHz
    const float k = 1000 / (clockRate_us * Rc * log ((R1 + R2) / R2));

**Note**: For high accuracy you should use the *measured* resistance values, not just the nominal ones.

---

Now with some fairly simple code we can use the constant **k** to work out the capacitance:

    /*
    Capacitance meter

    Author: Nick Gammon
    Date:   2 July 2013

    Pulse pin (D2): Connect to capacitor via 10K resistor (Rc)

    Reference voltage connected to D7 (AIN1) as per below.

    Measure pin (D6 - AIN0) connected to first leg of capacitor, other leg connected to Gnd.

    Like this:

    Capacitor to test:

    D2  ----> Rc ----> D6 ----> capacitor_under_test ----> Gnd

    Reference voltage:

    +5V ----> R2 ---> D7 ---> R1 ----> Gnd

    */

    const byte pulsePin = 2;   // the pin used to pulse the capacitor
    const float Rc = 10000;    // charging resistor
    const float R1 = 1000;     // between ground and D7
    const float R2 = 1800;     // between +5V and D7
    const float clockRate_us = 16;  // 16 MHz

    const float k = 1000 / (clockRate_us * Rc * log ((R1 + R2) / R2));

    volatile boolean triggered;
    volatile boolean active;

    volatile unsigned long timerCounts;
    volatile unsigned long overflowCount;

    ISR (TIMER1_OVF_vect)
    {
      ++overflowCount;               // count number of Counter 1 overflows
    }  // end of TIMER1_OVF_vect

    ISR (TIMER1_CAPT_vect)
      {
      // grab counter value before it changes any more
      unsigned int timer1CounterValue;
      timer1CounterValue = ICR1;  // see datasheet, page 117 (accessing 16-bit registers)
      unsigned long overflowCopy = overflowCount;

      if (active)
        {
        // if just missed an overflow
        if ((TIFR1 & bit (TOV1)) && timer1CounterValue < 0x7FFF)
          overflowCopy++;
        // calculate total count
        timerCounts = (overflowCopy << 16) + timer1CounterValue;  // each overflow is 65536 more
        triggered = true;
        digitalWrite (pulsePin, LOW);  // start discharging capacitor
        TCCR1B = 0;    // stop the timer
        }  // end if active
      }  // end of TIMER1_CAPT_vect

    void setup ()
      {
      pinMode (pulsePin, OUTPUT);
      digitalWrite (pulsePin, LOW);

      Serial.begin (115200);
      Serial.println ("Started.");
      ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
      ACSR = bit (ACIC);    // Analog Comparator Input Capture Enable
      DIDR1 |= bit (AIN1D) | bit (AIN0D); // Disable digital buffer on comparator inputs
      PRR = 0;
      }  // end of setup

    void startTiming ()
      {
      active = true;
      triggered = false;
      noInterrupts ();

      // prepare timer
      overflowCount = 0;            // no overflows yet
      // reset Timer 1
      TCCR1A = 0;
      TCCR1B = 0;
      TCNT1 = 0;      // Counter to zero
      // Timer 1 - counts clock pulses
      TIMSK1 = bit (TOIE1) | bit (ICIE1);   // interrupt on Timer 1 overflow and input capture

      // get on with it
      digitalWrite (pulsePin, HIGH);  // start charging capacitor
      // start Timer 1, no prescaler
      TCCR1B =  bit (CS10) | bit (ICES1);  // plus Input Capture Edge Select
      interrupts ();

      } // end of startTiming

    void finishTiming ()
      {
      active = false;
      Serial.print ("Capacitance = ");
      float capacitance = (float) timerCounts * k;
      Serial.print (capacitance);
      Serial.println (" nF");
      triggered = false;
      delay (3000);
      }  // end of finishTiming

    void loop ()
      {
      // start another test?
      if (!active)
        startTiming ();

      // if the ISR noted the time interval is up, display results
      if (active && triggered)
        finishTiming ();

      }  // end of loop

---

For extra accuracy the code uses the Input Capture Unit, which is something that remembers the exact value in Timer 1 when the match occurs. This avoids the delay of 2 to 3 µs while the ISR kicks into action.

---

### Results

I measured a few values using a capacitance-substitution box. To check on the box I measured also with a high-precision multimeter. The value on the right is what the sketch gave (rounded).

*(All values in nF)*

    Nominal    Meter     Sketch
    Value      Measure   Measure

        40         42        42
       100         98       102
       200        202       201
       300        312       313
       400        389       391
      1000       1004      1010
      2000       2011      2012
      3000       2950      2953
      4000       4160      4170

The sketch output certainly seems to be close to the nominal and measured values.

---

> What about using the internal voltage reference (1.1v) instead of AIN0? which one will be better as the 2xAA batteries voltage drops over time?

The voltage doesn't matter as it is not in the equation. It is the **ratio** that matters, and that will scale with battery drop (ie. the ratio between the two resistors will always be the same).

You need to use Vcc because it is turned on and off at an output pin (to start charging the capacitor).

---

> Also what is the difference between TIMER1_CAPT_vect which you used here and ANALOG_COMP_vect which you used in the example in your site?

If you are **not** using the Input Capture Unit, then you need to get the Analog Comparator interrupt. However if you use the Input Capture Unit then you use the Timer1 Capture Event which is triggered when you get the capture.

  [1]: https://i.stack.imgur.com/3uMaN.png
  [2]: https://i.stack.imgur.com/K1r42.png
  [3]: https://i.stack.imgur.com/snZkL.png


body:
I planning to add an anemometer to my small solar weather station.
I designed this system to run from a single 3.7v rechargeable battery and a solar panel so I have to calculate in more power drain.

What I don't really understand is do these anemometers consume any external power or just give out a voltage by themselves?

This one doesn't even have consumption specified:

https://www.adafruit.com/products/1733

For this Supply voltage : 5V - 24VDC:

http://www.ebay.com/itm/JL-FSX2-4-20MA-0-5V-Output-Wind-Speed-Sensor-Wind-Speed-Transmitter-Anemometer-/331521148973?hash=item4d3033482d

title: Does Anemometer consumes power?

Answers: 1

body:
If it runs on electricity it definitely consumes power, its only how much the real question is.

Since you are working with electronics I am going to assume that you have a multimeter, if you dont have one. Its about time you did, doesnt cost much and will save you a ton of time debugging.

Nearly every multimeter has an onboard ammeter (the accuracy will be mentioned in the instructions manual). You can use this to determine the current consumed, have a look at a tutorial from [sparkfun][1] on how to do this

  [1]: https://learn.sparkfun.com/tutorials/how-to-use-a-multimeter/measuring-current