message:
How to implement elapsed millis as the timer for my motor spinning time?

I have been using delay() as the function for my motor spinning time. However, at the same time, I need to calculate the rpm of my motor. Delay() function have to make it impossible for me to get the rpm whilst the motor spin. I have learned that I needed to use Elapsed millis as a replacement for delay() for my timing.

I have tried it and to no avail, I did not get the result in wanted. Yes, the motor spin according to the speed that I desired, however, it does not spin according to the time I wanted. It kept on spinning non-stop till I have to disconnect the power supply.

So, my question is, how do I implement the elapsed millis as my timer for my spinning motor?
please, guys, help me with this... Just guide me through and give me guidance.

This is my code that I have tried using elapsed millis. Any suggestion is welcome.

    #include <elapsedMillis.h>
    #include <Keypad.h>
    #include <Wire.h>  // Comes with Arduino IDE
    #include <LiquidCrystal_I2C.h>
    #include <Servo.h>
    Servo myservo;
    LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address
    elapsedMillis timeElapsed;

    const byte ROWS = 4; //four rows
    const byte COLS = 3; //three columns
    char keys[ROWS][COLS] =
    {
      {'1', '2', '3'},
      {'4', '5', '6'},
      {'7', '8', '9'},
      {'*', '0', '#'}
    };

    byte rowPins[ROWS] = {9,8,7,6}; //row pinouts of the keypad (L1, L2, L3, L4)
    byte colPins[COLS] = {5,4,3}; //column pinouts of the keypad (R1, R2, R3)
    Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

    void setup()
    {

      Serial.begin(9600);
      lcd.begin(20,4);
      myservo.attach(11);

       lcd.setCursor(0,0);
      lcd.print("S=");
      lcd.setCursor(0,1);
      lcd.print("T=");
      lcd.setCursor(0,2);
      lcd.print("S=");
      lcd.setCursor(0,3);
      lcd.print("T=");
      lcd.setCursor(10,0);
      lcd.print("S=");
      lcd.setCursor(10,1);
      lcd.print("T=");
      lcd.setCursor(10,2);
      lcd.print("RPM");

    }

     void loop()

    {

      int stage1speed = getTheNumber();
      lcd.setCursor(2,0);
      lcd.print(stage1speed);
      lcd.print("sv");
      int stage1time = getTheNumber();
      lcd.setCursor(2,1);
      lcd.print(stage1time);
      lcd.print("sec");

      int stage2speed = getTheNumber();
      lcd.setCursor(2,2);
      lcd.print(stage2speed);
      lcd.print("sv");
      int stage2time = getTheNumber();
      lcd.setCursor(2,3);
      lcd.print(stage2time);
       lcd.print("sec");

      int stage3speed = getTheNumber();
      lcd.setCursor(12,0);
      lcd.print(stage3speed);
      lcd.print("sv");
      int stage3time = getTheNumber();
      lcd.setCursor(12,1);
      lcd.print(stage3time);
      lcd.print("sec");

       if ( stage1speed > 0 && stage1time > 0 && stage2speed > 0 && stage2time > 0 && stage3speed > 0
            && stage3time > 0 )

       {

        if(timeElapsed <= 1000*stage1time)

        {

         myservo.write(stage1speed);

         }

        if(timeElapsed <= 1000*stage2time)

        {

         myservo.write(stage2speed);

         }

        if(timeElapsed <= 1000*stage3time)

        {

         myservo.write(stage3speed);

         }
      }

    }

    int getTheNumber()
    {
        char buffer[4];
        // Input up to 3 numbers until we find a * or #
        int i=0;
        while (1)
        {
            char key = keypad.getKey();

            // If it's a number AND we have space left, add to our string
            if ('0' <= key && key <= '9' && i < 3)
            {
                buffer[i] = key;
                i++;
            }
            // If it's a * or #, end
            else if ('#' == key && i > 0)
            {
                // Null terminate
                buffer[i] =0;
               int value = atoi(buffer);  // Convert to an integer
                break;
            }

        }
        return atoi(buffer);
        }

body:
`delay()` is only the tip of the iceberg. The problem with `delay()` is
that it is a _blocking_ function: nothing else can be done during the
delay. If you want to control your motor and at the same time be
responsive to the user, you must avoid blocking your program. This means
not only getting rid of `delay()`, but also getting rid of _any blocking
function_.

Here your problem is on `getTheNumber()`. This function blocks until the
user is done typing the number. Try to rewrite it in a non-blocking
fashion. For example, it could return `-1` on every call as long as the
user is not done typing the number. On the first call after the user is
done it would return the valid value. If you manage to write everything
non-blocking, then you `loop()` will restart very often, and the program
will work with no significant latency.

As for managing the servo stages, simplest thing  would be to write a
[finite state machine][FSM]. I would write it with four states: IDLE,
STAGE1, STAGE2 and STAGE3. The transitions STAGE1 → STAGE2 → STAGE3 →
IDLE would be time-based, using the `elapsedMillis` object to track the
time spent in each state. The transition IDLE → STAGE1 would be
triggered by the user input.

    static enum { IDLE, STAGE1, STAGE2, STAGE3 } state;
    switch (state) {
        case IDLE:
            if (userRequestedToStartAgain()) {
                myservo.write(stage1speed);
                state = STAGE1;
                timeElapsed = 0;
            }
            break;
        case STAGE1:
            if (timeElapsed >= stage1time) {
                myservo.write(stage2speed);
                state = STAGE2;
                timeElapsed = 0;
            }
            break;
        case STAGE2:
            if (timeElapsed >= stage2time) {
                myservo.write(stage3speed);
                state = STAGE3;
                timeElapsed = 0;
            }
            break;
        case STAGE3:
            if (timeElapsed >= stage3time) {
                myservo.write(idleValue);
                state = IDLE;
            }
            break;
    }

[FSM]: https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/


sender: user

message:
HC-SR04 distance measuring without delay?

I am using the HC-SR04 ultra sound sensor for Arduino. I have used the following code to calculate distance and it works perfectly.

      long duration;
      digitalWrite(trigger, LOW);
      delayMicroseconds(2);
      digitalWrite(trigger, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigger, LOW);
      duration = pulseIn(echo, HIGH);
      distance = (duration/2) / 29.1;

However I want to use three more of these sensors, for a total of four. This block of code will be called every time I want to find the distance of one of the sensors. I am worried however that `delayMicroseconds()` pauses the entire program and that I cannot perform other tasks in while the sensors are working (e.g. driving wheels, it's a robot). The following code is object oriented for each sensor.

    class distSensor{
       int trigPin;
       int echoPin;
       int distance;

       //Will be used in timer
       unsigned long previousMillis;

       public:
       distSensor(int tPin,int ePin){
       trigPin = tPin;
       echoPin = ePin;

       pinMode(trigPin, OUTPUT);
       pinMode(echoPin, INPUT);

       previousMillis = 0;
     }

     int calculateDistance(){

      //records time since program start
      unsigned long currentMillis = millis();

      long duration;
      digitalWrite(trigPin, LOW);

      //check if the previous time the method was called is greater than the interval of 2
      if(currentMillis - previousMillis > 2){
        digitalWrite(trigPin, HIGH);
        previousMillis = currentMillis;
      }

      //check if distance between current time and previous time it was called is greater than interval of 10.
      if(currentMillis - previousMillis > 10){
          digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      distance = (duration/2) / 29.1;
      }
      return distance;
     }
    };

In the `calculateDistance()` method I am trying to do the same thing as the first code but without `delay()` and instead a timer. But when I run the program it does not work and distance is read as 0. Can anyone help me rewrite the HC-SR04 code from the start that doesn't delay the whole program?

sender: assistant

body:
[`delay()`][1] causes the processor to do nothing but wait.  You need to switch to [`millis()`][2].

In your code, you need to "grab" the current time using `millis()` and store it in a variable.  Add the number of milliseconds that you want to wait to this variable - you will have to consider the case where this value will overflow for a complete solution. Then, in your code, you need to create an infinite loop where you check what `millis()` returns.  When your stored value and `millis()` match, it is time to execute the code that would normally come after the `delay()` call.

Here, [Arduino Playground - How and Why to avoid delay()][3], `delay()` and `millis()` are discussed in detail.

So that this answer will cover your question, consider placing all your events which need to be timed into this one infinite loop.  Also, consider keeping independent variables, one for each timed event, such that different events are timed independently.

  [1]: https://www.arduino.cc/en/reference/delay
  [2]: https://www.arduino.cc/en/reference/millis
  [3]: http://playground.arduino.cc/Code/AvoidDelay


body:
    enter code here
    #define ECHO 5        // Pin received echo pulse
    #define TRIGGER 6     // Pin sends shot pulse

    int distance; // the distance in cms
    unsigned long previousMicros = 0; // will sotre last time TRIGGER was updated
    long OnTime = 10; //microseconds of on-time
    long OffTime = 2; //microseconds of off-time
    unsigned long previousMillis = 0; //will store last time viewTime was updated
    int triggerState = LOW; // triggerState used to set it up
    long duration;
    void setup()
    {
      Serial.begin(9600);
      pinMode(ECHO, INPUT);
      pinMode(TRIGGER, OUTPUT);
    }

    void loop()
    {
      // check to see if it's time to change the state of the TRIGGER
      unsigned long currentMicros = micros();
      if((triggerState == LOW) && (currentMicros - previousMicros >= OffTime))
       {
         triggerState = HIGH; // turn it on
         previousMicros = currentMicros; // remember the time
         digitalWrite(TRIGGER, triggerState); // update the actual trigger
       }
       else if((triggerState == HIGH) && (currentMicros - previousMicros >= OnTime))
       {
         triggerState = LOW; // turn it off
         previousMicros = currentMicros; // remember the time
         digitalWrite(TRIGGER, triggerState); // update the actual trigger
       }

    duration = pulseIn(ECHO,HIGH  );
    Serial.println(distance);
    distance = ((duration*0.034)/2);
    Serial.print("distance: ");

    }

**this will run your code without delay but the problem is you will get a zero every time resulting from pulseIn() which from there on I dont know how to fix it yet**


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

    unsigned long currentMillis = micros();
    digitalWrite(Trig, LOW);

    if (currentMillis - previousMillis > 4) {
      digitalWrite(Trig, HIGH);
      previousMillis = currentMillis;
    }

    if (currentMillis - previousMillis > 12) {
      digitalWrite(Trig, LOW);
      previousMillis = currentMillis;
    }

    impulseTime = pulseIn(Echo, HIGH);
    distance_sm = impulseTime / 58; // convert to centimeters
    distance = distance_sm;


message:
Make action happen after time is passed using interrupts

I am trying to create a code which prints to the LCD a message once a certain time is passed.

    #include <Time.h>
    #include <TimeLib.h>
    #include <Adafruit_RGBLCDShield.h>
    #include <utility/Adafruit_MCP23017.h>
    Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

    void setup() {
      lcd.begin(16, 2);
      setTime(02, 10,00, 14, 03, 2016);

      //pinMode(13, OUTPUT);
      pinMode(2, INPUT);
      digitalWrite(2, LOW);
      attachInterrupt(0, blink, CHANGE);
    }

    void loop() {
      lcd.setCursor(0, 1);
      char time_out[16];
      sprintf(time_out, "u:u:u",hour(),minute(),second());//use %x to get hex
      lcd.print(time_out);

      int totalSeconds = (hour() * 3600) + (minute() * 60) + second();
      lcd.print(totalSeconds);
      if(totalSeconds > 7806) {
        digitalWrite(2, HIGH);
      }
    }

    void blink() {
      lcd.print("time passed");
    }

The `setup` uses the Time lib to set a date. It also  sets `pin 2` as an `INPUT` and sets it it `LOW`. The `attachInterrupt` checks if `pin 2 (0)`, changes, then function `blink` should execute.

In the loop, I am creating a string that prints out the time and displaying it to the LCD. I am also converting the time to seconds, so that I can easily compare two times. After 6 seconds (the timer starts at 7800), I am changing the value of `pin 2` to `HIGH`.

This should indicate a change in its state and should and trigger `blink`, but it does not. Can anyone spot the mistake I made? Thanks in advance.

body:
Since I don't have enough reputations to comment on your question I am going to drop my two cents here.

Since your question is a little bit vague, I am going to suppose that you don't want any external interrupts thus, you don't need to use the `attachInterrupt` function. I am going to suppose that there is no need to use timers' interrupts as well.

Have a look at the following code:

    #include <Time.h>
    #include <TimeLib.h>
    #include <Adafruit_RGBLCDShield.h>
    #include <utility/Adafruit_MCP23017.h>
    Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

    void setup() {
      lcd.begin(16, 2);
      setTime(02, 10,00, 14, 03, 2016);
    }

    void loop() {
      char time_out[16];
      lcd.setCursor(0, 1);
      sprintf(time_out, "u:u:u",hour(),minute(),second());//use %x to get hex
      lcd.print(time_out);

      int totalSeconds = (hour() * 3600) + (minute() * 60) + second();
      lcd.print(totalSeconds);
      if(totalSeconds > 7806) {
        blink();
      }
    }

    void blink() {
      lcd.print("time passed");
    }

You should know the following:

Commands inside `void loop()` is going to be executed for ever again and again. Especially `lcd.print(time_out);`. You had better refresh the LCD every 1 second.

After 6 seconds `blink()` is going to be executed many times (maybe forever) since it is inside the loop and `if(totalSeconds > 7806)` is going to be always true.

If you have any question let me know in the comment section.


body:
1.  To do what you want, pin 2 would need to be an output.  As an input you have no control over its state when you write it low.  It may be hanging there floating in a high state and when you write high to it and turn on the pullup that may or may not actually be a change of state.

2.  Doing a print to the LCD may not work in an ISR.  Remember that during the ISR all other interrupts are disabled and depending on how your lcd library works it may not print anything from inside the ISR.

3.  Even if it does print "time passed" upon being triggered by the line at the end of loop, a few microseconds later loop would repeat and that would be overwritten by the stuff that loop writes to the screen.  So even if it did work you'd never know.

Instead of having your ISR print something to the screen, have it turn on an led or something so you know it actually triggered.

Try this instead and see if it is closer to what you want: (uncompiled and untested as I don't have the libraries)

    #include <Time.h>
    #include <TimeLib.h>
    #include <Adafruit_RGBLCDShield.h>
    #include <utility/Adafruit_MCP23017.h>
    Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

    boolean passed = false;

    void setup() {
      lcd.begin(16, 2);
      setTime(02, 10, 00, 14, 03, 2016);

      //pinMode(13, OUTPUT);
      pinMode(2, OUTPUT);
      digitalWrite(2, LOW);
      attachInterrupt(0, blink, CHANGE);
    }

    void loop() {
      if (passed) {
        lcd.setCursor(0, 1);
        lcd.print("time passed");
        while(1);  // freeze here time is up
      }
      else {
        lcd.setCursor(0, 1);
        char time_out[16];
        sprintf(time_out, "u:u:u", hour(), minute(), second()); //use %x to get hex
        lcd.print(time_out);

        int totalSeconds = (hour() * 3600) + (minute() * 60) + second();
        lcd.print(totalSeconds);
        if (totalSeconds > 7806) {
          digitalWrite(2, HIGH);
        }
      }
    }

    void blink() {
      passed = true;
    }


message:
Play sound with speaker inside interrupt while a timer runs

I'm attempting to start a timer lasting a specific interval when the ultrasonic distance sensor measures a distance lower than 25 cm. Once that occurs, I want the speaker to make sound if the distance goes above 25 cm whilst the timer is running. I am attempting to use an interrupt to do this, but I'm having trouble.

This is what I have so far:

    void setup() {
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(interruptPin, INPUT_PULLUP);
      attachInterrupt(digitalPinToInterrupt(interruptPin), sensor, CHANGE);
    }

    int makeSound() { // This function creates the sounds
      ...
    }

    int echo() { // This function gets the distance the sensor is measuring
      ...
    }

    void loop() {
      distanceCm = echo();
      if (distanceCm < 25) {
        Timer();
      }
    }

    int Timer() {
      half_hour_millis = millis();

      while (millis() < half_hour_millis + interval) {
        // Here goes the code that I haven't written and was hoping you could help me with
      }
    }

    // My interrupt function
    void sensor() {
    }

body:
Andrew,

I think I see what you're trying to accomplish. I would try something like the following, and I'll explain afterward:

    boolean timerRunning = false;
    unsigned long start_millis;
    unsigned long end_millis;

    boolean tripped() //was int Start()
    {
      dist = echo1();
      if (dist < 25 && dist > 0) {
        return true;
      else
        return false;
    }

    void loop()
    {
      if(tripped())  //check for < 25cm
      {
        //if tripped and timer not running, start
        //keeping track of time
        if(!timerRunning)
        {
          timerRunning = true;
          start_millis = millis();
          end_millis = start_millis + half_hour;
        }
        //if timer already running, print millis
        else
        {
          Serial.println(millis()); //or Serial.pringln(millis()-start_millis);
                        // for time since timer started
        }
      }
      else  //not < 25cm, not tripped
      {
        //if not tripped and timer running, time for sound
        if(timerRunning)
        {
          timerRunning = false; //might as well stop timer
          alert();
        }
        //if timer not started and not tripped nothing to do
      }

      //finally, lets check time, if past half hour, stop tracking
      //elapsed time
      if(timerRunning)
      {
        if(millis > end_millis)
        {
          timerRunning = false;
        }
      }
    }//end void loop()

In general, you don't want to block the loop() from looping. Some of the Arduino functions do their processing outside that loop (the interrupt pin possibly too).

I know I'm not using the interrupt, but for a couple reasons. First, it looks like the pin can only change if you call your echo1() function, as you have to trigger the ultrasonic transmitter. Secondly, the state of the pin will not reflect the distance, only that it's receiving sound. As an aside, for what it looks like you were trying to do, you would have wanted to attach the interrupt and detach the interrupt only when the timer started or ended, as opposed to in the setup. Otherwise it could interrupt at any time, such as everytime the echo1() was called.

Hopefully my code comments help explain the flow. Basically I'm keeping track of the state of things, mostly with 'timerRunning'. Based on whether the timer is running and the ultrasonics are tripped (measuring less than 25cm), the appropriate actions are taken. The only way to stop the timer is the elapsing of half an hour, or the alert condition.

Double check my math, but i think there are 1,800,000 milliseconds in half an hour, so you will want to change your constant. Also, I don't know how long you plan on having your device run, but the millis() function will rollover back to 0 after about 50 days. Your end time will end up calculating out to less than the current time and the timer will not be able to run properly (will immediately stop) for that last half hour until rollover. Just something to keep in mind.

Hope this helps and good luck!


message:
exit status 1 expected primary-expression before 'int'

int temp=A0;
    #include<stdlib.h>
    #include <SoftwareSerial.h>

    #define SSID "rab"
    #define PASSWORD "rakesh1234"
    #define IP "184.106.153.149" // thingspeak.com
    String GET = "GET /update?key=B8B8E4FC1K541QZQ&field1=";
    SoftwareSerial monitor(0, 1); // RX, TX
    SoftwareSerial mySerial(5, 6); // RX, TX
    int p1=0,p2=0,p3=0;
    int i=0;
    int j=0;

    void setup() {
      pinMode(A0,INPUT);
      Serial.begin(115200);
      monitor.begin(115200);
      mySerial.begin(9600);
      sendDebug("AT");
      delay(2000);
      if(Serial.find("OK")) {
        monitor.println("RECEIVED: OK");
        Serial.println("RECEIVED: OK");
      }
      connectWiFi();
    }

    unsigned char buf[50];

    void loop() {
       while(!mySerial.available());
       if(mySerial.read() == '#') {
         for(int i=0;i<12;i++) {
           while(!mySerial.available());
           buf[i] = mySerial.read();
         }
         buf[3] =0;
         buf[7]=0;
         buf[11]=0;
         p1 = atoi((const char *)&buf[0]);
         p2 = atoi((const char *)&buf[4]);
         p3 = atoi((const char *)&buf[8]);
         delay(1000);
       }

       long int SensorValue=analogRead(temp);
       SensorValue=SensorValue*5000;
       SensorValue=SensorValue/1024;
       SensorValue=SensorValue/10;
       SensorValue=SensorValue*9;
       SensorValue=SensorValue/5;
       SensorValue=SensorValue+32;
       String tempF=String(p1);
       String tempFF=String(p2);
       String tempFFF=String(p3);
       String tempFFFF=String(SensorValue);

       for(int j=0;j>-1;j++) {
         **j= Serial.read(int p1, int p2, int p3);**
       }
       while(Serial.available()==j)
         updateTemp(tempF,tempFF,tempFFF,tempFFFF);
       while(1) {}
     }

     void updateTemp(String tempF1 ,String tempF2, String tempF3,  String tempF4) {
       String cmd = "AT+CIPSTART=\"TCP\",\"";
       cmd += "api.thingspeak.com";
       cmd += "\",80";
       sendDebug(cmd);
       delay(1000);
       if(Serial.find("Error")) {
         monitor.print("RECEIVED: Error");
         Serial.print("RECEIVED: ERROR");
         return;
       }
       cmd = GET;
       cmd += tempF1;
       cmd += "&field2=";
       cmd += tempF2;
       cmd +="&field3=";
       cmd +=tempF3;
       cmd +="&field4=";
       cmd +=tempF4;
       cmd += "\r\n";
       Serial.print("AT+CIPSEND=");
       Serial.println(cmd.length());
       if(Serial.find(">")) {
         monitor.print(">");
         monitor.print(cmd);
         Serial.print(cmd);
       } else {
         sendDebug("AT+CIPCLOSE");
       }
       if(Serial.find("OK")) {
         monitor.println("RECEIVED: OK");
       } else {
         monitor.println("RECEIVED: Error");
       }
     }

     void sendDebug(String cmd) {
       monitor.print("SEND: ");
       monitor.println(cmd);
       Serial.println(cmd);
     }

     boolean connectWiFi() {
       Serial.println("AT+CWMODE=1");
       delay(2000);
       String cmd="AT+CWJAP=\"";
       cmd+=SSID;
       cmd+="\",\"";
       cmd+=PASSWORD;
       cmd+="\"";
       sendDebug(cmd);
       delay(1000);
       if(Serial.find("OK")) {
         monitor.println("RECEIVED: OK");
         return true;
       } else {
         monitor.println("RECEIVED: Error");
         return false;
       }
     }

This is my code. I am getting an error as "exit status 1
expected primary-expression before 'int'"

Please help me.

Thank you.

body:
You are doing Serial.read() wrong with:

    Serial.read(int p1, int p2, int p3);

`Serial.read()` takes no parameters per https://www.arduino.cc/en/Serial/read

Maybe you want to try `parseInt()` instead?


body:
Your problem is that your are using asterisks ("*")

       for(int j=0;j>-1;j++) {
         **j= Serial.read(int p1, int p2, int p3);**
       }

The asterisk in C/C++ is the **pointer operator**. You use to get the value pointed by a pointer.

The expression `**j` means that `j` is a pointer to a pointer that points something. That's is meaningless here.

Then, the last `**` is readed as another pointer to a pointer, and the compiler is expecting a variable or expression that give the value for the pointer, but found "}", which is an error.

You probably tried to comment out that line of code after the compiler barks at the `Serial.read()`, which, as Dave X pointed out, is illegal, because `Serial.read()` takes no arguments.

And, the syntax `function(int x)` is only use for declaring a function, not for calling one.


message:
What are the problems with using an Arduino in a production environment?

I am thinking about making a real project using arduino to earn money.

What could be the objective reasons (from both a technical and a business perspective) to not use an Arduino in a real profitable project?

body:
As a rule, no it's not a great idea.

Arduino boards are a prototyping platform. They are designed to make trying ideas out easy, not for permanent installation in a device. That's not to say you can't permanently install it in something of your own making, but when it comes to making a professional product it's not good, for a number of reasons:

1. An Arduino board is expensive compared to a plain MCU.
2. It's not a professional image.
3. It's not (typically) rugged and reliable enough.
4. Manufacturing something around a board like an Arduino is expensive.

The most professional way of using an Arduino would be to use something like an Arduino Mini and directly mount it on a custom PCB. But since you are making a custom PCB anyway, why would you incur the extra expense of an Arduino board when it is far cheaper to just build the required components directly into your board design? Also, when bulk manufacturing, you need to have as much of the build automated (i.e., surface mount to be populated by a pick-and-place machine) in order to keep costs down, and having to manually mount an Arduino onto a board adds extra expense (you have to pay a person to do the job themselves).


body:
> I want to know if there is anyone that has used Arduino boards in a real project?

I have seen it being done, quite a few times.

> What are the problems that you have faced?

Pros:

1. quick to market;

2. low cost accessories;

3. large code base to drop from;

4. ...

Cons:

1. only workable for certain applications -> high cost per mcu (vs. bare chips), no possibility of passing certification of any rigor, no respect from others / clients, ...

2. quite inflexible an eco-system: porting code to / from others can be problematic.

3. poor project management capabilities.

4. ...

Each of those pros / cons can be addressed and may not be relevant for your particular application.


message:
How to pull a pin low?

On the instructions for [this motor driver](https://learn.sparkfun.com/tutorials/easy-driver-hook-up-guide), it says that motors can be put to sleep by "pulling a pin low".

> **SLP** - Logic Input. When pulled LOW, outputs are disabled and power consumption is minimized.

I'm guess this means connect to ground? How could I trigger that via my Arduino board?

body:
Connect it to an IO port and set it to OUTPUT and LOW. That's what it means to "pull low".

It helps if you understand how an IO port works. [This may help you.](https://hackingmajenkoblog.wordpress.com/2017/03/20/what-exactly-is-a-gpio-pin/)


message:
Multiple connections on the same pin

I want to connect an arduino uno both to a TGAM module: http://www.seeedstudio.com/document/pdf/TGAM Datasheet.pdf
and a bluetooth shield. The arduino is to receive data from the TGAM module and sent it to an android device. The problem is I should connect the bluetooth and the TGAM to the same pins on the arduino. Is that a problem (I am still a novice, doing my research)? If it is a problem what is the work around?

**Arduino <> TGAM**

Arduino RX (0) <> TGAM T (TX)

Arduino TX (1) <> TGAM R (RX)

Arduino 3.3V <> TGAM + (VCC)

Arduino GND <> TGAM - (GND)

**Arduino <> HC-06**

3.3v    <> VCC

GND     <> GND

TXD     <> RXD

RXD     <> TXD

body:
No, you cannot use one pin (or set of pins) for two functions like that.

To communicate with two serial devices you will need two serial ports. It's possible to (just about) emulate one in software using the SoftwareSerial library. It's not wonderful though - personally I would use a chip that has multiple UARTs in it.


message:
Arduino EEPROM retains old data after flashing with a new program

I have a custom 5V 16Mhz Arduino Uno (a breadboard Uno of sorts) that runs the grbl firmware. After the initial flashing I can see all the settings (through the serial monitor) and everything works. However, if I make any changes to the firmware files and re-flash it, I can see that the old settings values have not been replaced with the new ones. I can only assume that these values are in the EEPROM and are not being erased on every re-flash cycle. I then tried the `eeprom_clear` program from Examples in the Arduino IDE and then re-flashed with the new firmware settings, after which I can see the new settings values.

I did some [digging][1] and found that the EESAVE fuse is responsible for this. However the Uno does have this fuse bit unprogrammed (set to 1). Why then am I able to see the old EEPROM settings and have to explicitly run an eeprom clear program before re-flashing with the updated firmware?

  [1]: https://arduino.stackexchange.com/questions/11846/is-eeprom-persisted-across-program-flashes

body:
Flash isn't EEPROM. When you reprogram the flash it doesn't touch the EEPROM.

It's controlled by the `-U...` flag to `avrdude`:

    avrdude ... -Uflash:w:<hex file>

If you want to set the EEPROM to something specific you can use `avrdude` to program an EEPROM file if the bootloader supports it (not sure it does, so you may need a programmer for it):

    avrdude ... -Ueeprom:w:<hex file>


body:
The -e parameter in avrdude should only erase the EEPROM if the fuse bit

Preserve EEPROM memory through the Chip Erase cycle; [EESAVE=0]

is not set. However it appears it is not possible to SET this fuse bit. (at least not with AVRDUDESS.


message:
Arduino Uno with UsbSerial Android library w/ baud rate over 9600?

I am having no issues talking to Android at baud rate of 9600. But once I raise the baud rate to anything higher Android seems to become deaf. When I try to read the Serial output using putty all seems fine.

Has anyone had success with baud rate over 9600 when talking to Android?

I am using the [felHR85/UsbSerial][1] library.

  [1]: https://github.com/felHR85/UsbSerial

body:
I have no enough reputations to make a comment so I will drop my two cents here.

Are you changing the baudrate at both sides?

I have been using the arduino's built-in UART library for a while using different baudrates with no problems. Your problem could be an issue related to the library you are using.


body:
Seems like there is [a bug][1] in the library.

  [1]: https://github.com/felHR85/UsbSerial/issues/91


message:
Arduino State Machine code flow

New to FSM, can someone explain how the flow works? If I use a case scenario in a loop, how is an external change detected and brought back to the loop?
Is all of the code/inputs, etc to be included within the case statements?

Still having a few problems. I have modified my code to include some of the suggestions. You can see that I added some print statements to allow me to monitor execution, but I can't get it to obey, such as print "trigger" when the PIR sensor is HIGH. Anyone available to explain my error(s)? I added a void check() just to bypass the keypad (not connected).

    //////////////////////////// Initialize & Includes //////////////////////////
    #include "SIM900.h"
    #include "sms.h"
    #include "Keypad.h"
    #include <GSM.h>
    SMSGSM sms;
    //To change pins for Software Serial, use the two lines in GSM.cpp.
    int PIR_SensorPin = 2;
    int LED_OutPin = 11; //green
    int Alarm_OutPin = 12; //red
    int alarm_count = 0;
    int switchPIN = 3; // alarm on test
    char keypadPIN;
    int z = 0;
    int i = 0;
    int waitTime = 5000;

    //////////////////////////// Setup Keypad //////////////////////////
    const byte ROWS = 4; //four rows
    const byte COLS = 4; //four columns
    char keys[ROWS][COLS] =
    {
      {
        '1', '2', '3', 'A'
      }
      ,
      {
        '4', '5', '6', 'B'
      }
      ,
      {
        '7', '8', '9', 'C'
      }
      ,
      {
        '*', '0', '#', 'D'
      }
    };
    byte rowPins[ROWS] = {
      6, 7, A2, A3 // row pin# on keypad to Arduino pin#, ie Row Pin #1 goes to Arduino Pin #6, etc.
    }; // connect to the row pinouts of the keypad
    byte colPins[COLS] = {
      3, A0, A1, A4
    }; // connect to the column pinouts of the keypad
    Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );
    const char PIN[5] = {
      '9', '6', '7', '9', '#'
    }; // PIN number
    char key_input[5] = {
      0, 0, 0, 0, 0
    }; // used for comparison

    //////////////////////////////// Setup ///////////////////////////////////
    void setup() {
      Serial.begin (9600);  // Establish Serial connection;
      pinMode (LED_OutPin, OUTPUT);     // Set pinMode.
      pinMode (Alarm_OutPin, OUTPUT);   // Set pinMode.
      pinMode (PIR_SensorPin, INPUT);   // Set pinMode.
      digitalWrite (LED_OutPin, LOW);   // Set output pins to LOW for start.
      digitalWrite (Alarm_OutPin, LOW); // Set output pins to LOW for start.
      digitalWrite (PIR_SensorPin, LOW);
      Serial.println ("Studio Alarm starting up."); // Serial message that GSM shield is starting up
      if (gsm.begin(4800)) {    // Set GSM shield to recommended 4800 baud rate.
        Serial.println ("Status = Network READY");
        digitalWrite (LED_OutPin, HIGH);
      }
      attachInterrupt (digitalPinToInterrupt (2), trigger, CHANGE); // PIR as interrupt
      // Could make use of the interrupts by checking in the interrupt if the state is "Ready" and
      // then setting the state to "Alarm".
      Serial.println ("System Ready");

      keypadPIN = HIGH;
    }

    //////////////////////////// State Setup //////////////////////////
    enum STATE {
      Ready, //system acknowledges trigger
      Unarmed, //system unarmed via keypad entry setting keypadPIN = LOW
      JustActivated, //PIR-triggered interrupt
      Alarm // confirm system unarmed then goto unarmed state else start alarm
    };
    STATE systemState = Unarmed;
    long timeGettingArmed;

    /////////////////////////// Trigger ///////////////////////////////
    void trigger() {
      systemState = JustActivated;
    }

    //////////////////////////// State Machine //////////////////////////
    void loop() {
      check ();
      switch (systemState) {Serial.println("switch");
        case Ready:
          if (PIR_SensorPin == HIGH) {Serial.println("PIR_Sensor");
            Serial.println("triggered");
            systemState = Alarm;
          } else if (keypadPIN == LOW) {
            systemState = Unarmed;
          }
          break;
        case Unarmed:
          if (keypadPIN == HIGH) {Serial.println("keypadPIN=HIGH");
            // Serial.println("Unarmed");
            timeGettingArmed = millis();Serial.println(timeGettingArmed);
             systemState = JustActivated;
          }
          break;
        case JustActivated:Serial.println("JustActivated");
          if (timeGettingArmed + waitTime < millis()) {
            Serial.println("Ready");
            systemState = Ready;
          }
          break;
        case Alarm:
          if (keypadPIN == LOW) {Serial.println("keypadPIN=LOW");
            systemState = Unarmed;
          } else {
            beep();
          }
          break;
      }
    }

    //////////////////////////// Alarm //////////////////////////
    void beep() {
      Serial.println("at beep");
      // (sms.SendSMS("8656171435", "*** Motion Detected in Studio! ***"));
      Serial.println ("MOTION detected: SMS Sent");
      for (alarm_count = 0; alarm_count <= 5; alarm_count++) { // Cycle outputs if triggered
        digitalWrite (Alarm_OutPin, HIGH); delay (1000); // On/Off/On/Off/Off
        digitalWrite (Alarm_OutPin, LOW); delay (500);
        digitalWrite (LED_OutPin, HIGH); // delay (1000);
        Serial.println (alarm_count);
      }
      systemState = Ready;
    }

    void check() {
      if (switchPIN == HIGH) {
        keypadPIN = LOW; // Unarmed
      }
      else {
        keypadPIN = HIGH; // Ready/Armed
      }
    }

body:
### MCU State Flow
1. State ( Model )
2. User/Machine Output ( View )
3. User/Machine Interruption ( Events )
4. State Changers ( Controller )
5. _goto_ 1.

Breakdown of how it works:

\#1. **State**. You start with a known finite state, which is the overall mode of operation for that piece or pieces. For a `switch()`-driven machine, it's a number, typically named by an integer constant for better readability.

\#2. **Output**. Based on the state, you make certain things happen. These adjustments can be done in the `switch()`, or in the `loop()` as they notice state changes. You can also write explicit sub-routines to call from the switch() to keep code tidy. You can _read_ the state from any point in the program, even interrupts if needed.

\#3. **Events/Interrupts**. Lying in wait, these parts spring into action when something happens that the program needs to know. Both human-origin (ex: button press) and machine-origin (ex: SD card error) fall into this group. They can set flags and publish notifications to the _controller_ that something has happened, but they MUST NOT set the state directly. The last point cannot be under-emphasized. If you start "cheating" and updating state outside of the controller, you  create another point of failure and another stop along the debug/enhancement tour.

\#4. **State Changing `switch()` (Controller)**.  This is where the actions meet the state. Only here should you change state to a new one, based on outside flags set by events. If your `switch()` is at the top of `loop()`, and you `return` in each `case`, you can call `loop()` from other points in the code to fire a state change immediately, but i like to name it in a `void()` and call it from `loop()`. The switch code should be lightweight and never use `delay()`. Lastly, most of the time a `case` does nothing, because no outside condition has changed that merits reaction, and it `break`s or `return`s right there. When something important does change, the code below that early-exit conditional performs as a state change event handler.

<br>

# Why bother

It can be a bit much at first, and seem like it's not worth the 5-10 mins up-front to name constants and write out all the `switch` bolierplate. I'm a lazy coder, and I still use this because it saves me a ton of time at every point in time besides those first 10 minutes.

Since things can only change in one place, you know exactly where to debug. It's simple to dump the outside values a `case` examines to the serial (remove before "launch"), rather than finding that chunk of code in the ether. Doing it all in one place makes it trivial to log when and what with each state change. With minor additional code you can even _undo_ state changes, which can be a boon for users. Such actions are not risky because every part of the outside code knows what to do.

It breaks up tedious chains of semi-related action into independent pieces. You won't need lots of nested `if()`s if you follow the above guidelines. Even if you're not a long-time developer, simply following this pattern and slopping/pasting all the other code together, your program will be better in the end and faster and easier to build along the way.


message:
Liquid Crystal LCD Display Prints f in all rows and columns

The problem is that the Liquid Crystal LCD display only prints "f" on every row and every column.

When I tell it to print something, then the display prints "f" on every square(row, column) for a brief second, then each square shows three white bars stacked up parallel to each other (quite like an "=" sign except that there's one more bar on top").

I am also using a tmrpcm library, so I'm guessing that interrupts might have to do with this, but I have no idea how to solve the problem.

The link to the tmrpcm library is as follows: https://github.com/TMRh20/TMRpcm

Thank you so much. I need to get this done by tomorrow 8 A.M., so I'm pretty desperate.

    #include <LiquidCrystal.h>
    #include <SD.h>                      // need to include the SD library
    //#define SD_ChipSelectPin 53  //example uses hardware SS pin 53 on Mega2560
    #define SD_ChipSelectPin 10  //using digital pin 4 on arduino nano 328
    #include <TMRpcm.h>           //  also need to include this library...

    TMRpcm tmrpcm;   // create an object for use in this sketch
    char mychar;
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    volatile int pauseOnOff;

    void setup(){

      tmrpcm.speakerPin = 9; //11 on Mega, 9 on Uno, Nano, etc

      if (!SD.begin(SD_ChipSelectPin)) {  // see if the card is present and can be initialized:
        Serial.println("SD fail");
        return;   // don't do anything more if not
      }
      else{
        Serial.println("success!");
      }

      tmrpcm.play("Closer.wav");

      lcd.begin(16, 2);

      lcd.print("hello, world!");
    }

    void loop(){

    }

body:
I don't know the source of the problem, but here are a few things that might help diagnose where the problem begins or what it is due to.

(a) To track execution progress, and detect which statement, if any, ruins LCD operation:  Create a routine to display current line number in code to LCD and Serial; make a macro `ss` to use for invoking that routine; invoke the macro before and after each line containing a `tmrpcm` action by calls like `ss;`.  See following example.

    void shoLine(int line) {
      Serial.println(line);
      lcd.home ();     // Set cursor to 0,0
      lcd.print(line);
      lcd.print(' ');
      delay(200);  // /Delay long enough to see stuff appear
    }
    #define ss shoLine(__LINE__)

Note:  Move `lcd.begin(16, 2);` to be the first statement in `setup()` when using this method of debugging.

(b) If you find that the first few LCD calls are ok and then LCD output stops working, try turning off interrupts during LCD output.  That is, put a `cli()` or `noInterrupts()` call before an `lcd.print()`, and an `sei()` or `interrupts()` after it, and see if it then works.  If so, that might serve as a last-ditch workaround.  (I don't know whether LCD output routines use any interrupts; I doubt they do; but if they do, this method won't work.)

(c) If the LCD doesn't display correctly at all, even before the first `tmrpcm` action, it may be that the combination of `tmrpcm` with other code is using too much memory.  Carefully check the memory-usage reports when you compile your sketch.


message:
Slave SPI does not work

I am trying to use both an SRAM (23LC1024) and SD card reader on an SPI bus.

My connections (for SPI):

- Arduino pin 11 (MOSI) -> SRAM pin 5 (SI/SIO0)
- Arduino pin 12 (MISO) -> SRAM pin 2 (SO/SIO1)
- Arduino pin 13 (SCK ) -> SRAM pin 6 (SCK)
- Arduino pin 10        -> SRAM pin 1 (CS )

In this way, I can read data from the SRAM.

To connect the SD I connected:

- SRAM pin 2 (SO/SIO1) -> SD MISO
- SRAM pin 5 (SI/SIO0) -> SD MOSI
- SRAM pin 6 (SCK    ) -> SD SCK
- Arduino pin 9        -> SD CS

Currently the SD card works, but read-byte commands to the SRAM always gives the same (wrong) value.

If I remove the wire between SRAM pin 2 and SD MISO the SRAM gives correct values, but the SD card does not have a MISO connection and seems to always return the same data (but still functions).

I also tried to first make the connections from the Arduino to the SD and than to the SRAM (but same result, not working).

What am I doing wrong?

Update: The problem is solved, however I do not understand why. I reconnected all pins, removed the shield to access the SRAM directly which worked. Than I put the shield back on (and moving the pins back) ... maybe it was something stupid that one pin did not have good contact. I'm sorry for the inconvenience.

New question (related):

Now it works with the Data logger shield, but not with the (cheap) SD reader breakout cards.

However, my eventual solution needs more proto space than is available on the Data logger shield.... do I really need to use a complete shield (and later the Arduino Mega), and a Mega proto shield ... that will be a big box.
While for the data logger, I don't need the RTC neither.

body:
It doesn't sound like you are doing anything wrong as such, it all sounds fine.

However SD cards, certainly some cheap ones, don't like to play nicely with other devices on a shared bus. Also some SD card adapters with level shifting don't play nicely.

By not playing nicely I mean tri-stating the MISO line in a timely fashion (or at all in some cases) which stops any data getting out of other devices, and can even cause damage in some cases.

You should check out the level shifting on the SD card adapter to see if it has tri-stating control of MISO (if it is shifting that line, not all do), try other brands of SD cards, and maybe add your own tri-state buffer to the SD card signals.


message:
How to load program into Arduino pro mini using FTDI cable?

Do we need a ftdi basic board to connect a ftdi 232R USB - TTL serial level converter cable via a 6 pin 0.1" male header into an Arduino pro mini/ nano 328 to upload the sketch?

body:
**For the Arduino Nano:**

**NO**, the Nano already includes the USB-to-TTL conversion circuitry. Just use the USB connector as you would with a Uno.

**For the Arduino Pro Mini:**

**YES**, you need an external breakout board to perform USB-to-TTL conversion. This board may use the FT232RL chip, but also any other equivalent one like the CH340G. You only need to have the adequate driver in your computer and you'll be set.

**NOTE:**

If you have "converter cable" you might not need a breakout board because this kind of cable already includes the FT232R (or equivalent). You don't need to use this cable with the Nano.


message:
Programming standalone Atmega328p-PU with NE555N timer IC

I know I may sound a little idiotic to ask, but as I have seen in the internet that to program a standalone Atmel chip like that from of the Arduino's, you need 2 22pF ceramic capacitors and a 16mhz oscillator. As the oscillator is needed is clock the frequency of the chip, so a timer IC should work just fine, isn't it? or do I have wrong information?

body:
Yes, you could use a 555. You can also go even simpler and use an RC network. Even simpler still is to use the 1MHz RC network built in to the chip.

The main drawback of these methods, and the 555 particularly, is that of stability. Using a crystal and capacitors you can get very accurate timing at high frequencies. Using a 555 you can get ballpark timing at low frequencies. Fine if all you want to do is blink an LED, but as soon as you need to do anything that requires good timing it all falls apart. That includes things like using the UART for which accurate timing is at the heart of its operation.

The internal oscillator is better in this respect since it can be calibrated using the OSCCAL register. However changes in ambient temperature can cause unacceptable drifting of the clock frequency.


body:
The default configuration of these chips, as they come from the factory,
is to use their internal 8 MHz RC oscillator downscaled at 1 MHz. So you
**do not** need any extra oscillator to program them.

Once you program the chip the first time, _if_ you configure it to use
an external resonator/oscillator, then **you do need** to have that
attached in order to _reprogram_ the chip.

A 555 may be able to run the chip, but if you want to reprogram it, the
programmer may not cope well with the extra-low frequency the chip would
be running at.


body:
**No, you won't be able to build a 16 MHz clock signal using a 555 timer.** That's far beyond the 555 capabilities (see N.B.).

If you could squeeze out of the 555 a mere 1 MHz (which I seriously doubt), the clock stability and jitter would be so bad that it won't be usable but for simple sketches not requiring any timing accuracy. At that point, you would be far better off using the internal 1 MHz RC network of the ATmega328P as Majenko says, because you would at least save the 555 and its associated components.

Also, a 555-based clock would consume much more power than any of the alternatives already available to you (internal oscillator, external crystal...). Even the CMOS version.

My recommendation: **forget about it, it's not worth it**.

**NOTE BELOW:**

NE555N is a BJT version of the 555. BJTs suffer from what's called "storage time", a charge accumulation in the base that severely limits switching time. The [NE555N datasheet][1] states a storage time of about 10 microseconds (p.10), which limits the switching frequency to about 100 kHz.

TLC555 is a CMOS version of the 555. Because it uses FETs, its maximum switching frequency is much higher. The [TLC555 datasheet][2] (p.6) states that a typical value for the maximum switching frequency is 2.1 MHz (and at least > 1.2 MHz).

  [1]: http://www.ti.com/lit/ds/symlink/ne555.pdf
  [2]: http://www.ti.com/lit/ds/symlink/tlc555-q1.pdf


body:
It depends on how you're programming it.

If you're using a bootloader to accept programming commands via a serial connection then you will need to use the clock method specified by the fuses currently programmed, since the chip at that point will actually be running code programmed on it.

If you're using ISP to program the chip out-of-band then you can apply a clock source directly to the XTAL1 pin as shown in the "Serial Downloading" subsection of the "Memory Programming" section of the datasheet. In this case you will need to adhere to the timing information given at the end of the subsection.


message:
Strings becoming empty (Arduino Uno)

I'm running a modifed code on Arduino Uno + WiFi shield (updated), and I have seen strange behaviors with `String` ; here is my code, the goal is to parse a HTML request to know which page was requested :

    String line = client.readStringUntil("\n");
    Serial.print("Line : [");
    Serial.print(line);
    Serial.println("]");

    String cmd = line.substring(0, 3);
    Serial.print("Command : [");
    Serial.print(cmd);
    Serial.print("]");

My problem comes from what appears in the console :

    Line : [GET / HTTP/1.1
    Host: 192.168.43.200
    Connection: keep-alive
    Cache-Control: max-age=0
    Upgrade-Insecure-Requests: 1
    User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
    Accept-Encoding: gzip, deflate, sdch
    Ac]
    Command : []

I was expecting the `cmd` variable to contain `GET`, and I do not understand why it contains nothing.

I suspect this behavior comes from the lack of RAM (compiler says there are only 670 bytes available for local variables), but if it's the case, I do not know how to solve it, as I'm pretty inexperienced in C++ and I need to store a String containing the values that are sent as a reply to the HTTP request.

PS. I'm also wondering why the `client.readStringUntil("\n")` method sends the full request instead of only the first line.

body:
In general, you don't want to be copying strings around when you don't have to because it's inefficient. For parsing things like command lines, you can often just work with the existing `String` (or better yet, `string`; see [Majenko's tutorial](https://hackingmajenkoblog.wordpress.com/2017/04/08/splitting-up-text-in-c/)).

In this particular example, you have a string and you want to know if it's an HTTP `GET` command. That's simple enough; the first four characters will be `GET ` (we check the space on the end because we don't want to interpret `GETMORE /foo` as a `GET` command).

This is extremely easy:

    String s = "GET /foo/bar";

    if (s.startsWith("GET "))
        Serial.println("GET command");
    else
        Serial.println("Not GET command");

For stuff in the middle of a string you obviously can't use `startsWith`, but there are [other functions](https://www.arduino.cc/en/Reference/StringObject) that can help. For example, once you know it's a GET command, you know that the URL starts at position 4 (the 5th character, since counting starts at 0). You could test to see if it starts with '/foo' with

    if (s.indexOf("/foo") == 4)
        Serial.println("Path starts with /foo.");
    else
        Serial.println("Path doesn't start with /foo.");

That said, while this kind of thing is workable for quick tests, in the long run you probably want to move towards parsing in C in the way that Majenko's tutorial above talks about, and likely parsing as much as possible as you do the reading (rather than reading everything into memory and then parsing it) due to HTTP requests being relatively large compared to the memory you have to handle them.


message:
Actual baud rate of UNO R3 Firmata protocol

Probably a silly question. But the Internet is confusing me.

The Firmata website says the default baud rate is 57600. But AFAIK, the baud rate set for UNO R3 is 9600(In Windows device manager, it say so). I'm making the Firmata client program and have to set the baud rate. I'm confused whether it's similar to the serial protocol or not.

[Using the StandardFirmata sketch]

body:
The baud rate is whatever the program opening the port requests it to be. The stuff in the device manager is only the default used if nothing else is specified when the port is opened.

And the Firmata protocol just squirts bytes over serial. It's based upon the MIDI protocol, which is just serial.


message:
Get Speed Using GPS Neo with TinyGPS++

I am trying to get the current speed of my car using the GPS Neo, but my code always returns that the speed from the GPS is invalid. The green led of the GPS Neo is blinking. What is the isValid() function? Below the code:

    #include <EEPROM.h>
    #include <TinyGPS++.h>
    #include <SoftwareSerial.h>
    //LOAD WIRE LIB
    #include<Wire.h>
    static const int RXPin = 10, TXPin = 9;
    static const uint32_t GPSBaud = 9600;
    // The TinyGPS++ object
    TinyGPSPlus gps;
    // The serial connection to the GPS device
    SoftwareSerial ss(RXPin, TXPin);
    //***************************************************************
    int aux = 0;
    int vel_prog = 20; //programed SPEED
    float vel_atual;//  actual SPEED
    int val_inc = 0;
    int val_dec = 0;
    int led0 = 2;//led pin
    int led20 = 3;//led pin
    int led60 = 4;//led pin
    int led80 = 5;//led pin
    int ledsinal = 6;//led pin
    int buzzer = 7;//buzzer pin
    int incrementa = 8;//button pin
    //****************************************************************
    void setup()
    {
      Serial.begin(115200);
      ss.begin(GPSBaud);
      pinMode(incrementa, INPUT);
      pinMode(led0, OUTPUT);  // declare LED as output
      pinMode(led20, OUTPUT);  // declare LED as output
      pinMode(led60, OUTPUT);  // declare LED as output
      pinMode(led80, OUTPUT);  // declare LED as output
      pinMode(ledsinal, OUTPUT);  // declare LED as output
      pinMode(buzzer, OUTPUT);  // dbuzeer
      delay(10);
    }

    void loop()
    {

      smartDelay(1000);
      val_inc = digitalRead(incrementa);  // read increment button
      if (val_inc == 1) {
       if (vel_prog > 80) {
          vel_prog = -20;
       }
          vel_prog = vel_prog + 20;
      }

      if (vel_prog == 0) {
        digitalWrite(led0,HIGH);
        digitalWrite(led20,LOW);
        digitalWrite(led60,LOW);
        digitalWrite(led80,LOW);
      } else if (vel_prog == 20) {
        digitalWrite(led0,LOW);
        digitalWrite(led20,HIGH);
        digitalWrite(led60,LOW);
        digitalWrite(led80,LOW);
      } else if (vel_prog == 60) {
        digitalWrite(led0,LOW);
        digitalWrite(led20,LOW);
        digitalWrite(led60,HIGH);
        digitalWrite(led80,LOW);
      } else if (vel_prog == 80) {
        digitalWrite(led0,LOW);
        digitalWrite(led20,LOW);
        digitalWrite(led60,LOW);
        digitalWrite(led80,HIGH);
      }

      if (gps.speed.isValid()){
      Serial.print(gps.speed.kmph());
      } else {
      Serial.print("*");
      }

     if (gps.speed.isValid()) {
      if (gps.speed.kmph() >= vel_prog && aux == 0) { //comparacao da velocidades
        digitalWrite(ledsinal, HIGH);  // turn LED OFF
        tone(buzzer, 2200);
        delay(5000);
        digitalWrite(ledsinal, LOW);  // turn LED OFF
        noTone(buzzer);
        aux = 1;
      }
    }
    }

    static void smartDelay(unsigned long ms)
    {
      unsigned long start = millis();
      do
      {
        while (ss.available())
          gps.encode(ss.read());
      } while (millis() - start < ms);
    }

body:
These lines of code will wreak havoc with reading the GPS data:

    tone(buzzer, 2200);
    delay(5000);
    digitalWrite(ledsinal, LOW);  // turn LED OFF
    noTone(buzzer);

The Arduino is "blocked" at these lines for seconds.  During that time, the GPS keeps babbling and eventually overflows the input buffer.  The next call to `smartDelay` only waits for 1 second, and it may not get a complete sentence.

Here is a [NeoGPS](https://github.com/SlashDevin/NeoGPS) version of your sketch that does not block:

    #include <EEPROM.h>
    #include <NMEAGPS.h>
    #include <NeoSWSerial.h>
    #include <Wire.h>

    NMEAGPS gps;

    static const int RXPin = 10, TXPin = 9;
    static const uint32_t GPSBaud = 9600;
    NeoSWSerial gpsPort(RXPin, TXPin);

    //***************************************************************
    int aux = 0;
    int vel_prog = 20; //programed SPEED
    float vel_atual;//  actual SPEED
    int val_inc = 0;
    int val_dec = 0;
    int led0 = 2;//led pin
    int led20 = 3;//led pin
    int led60 = 4;//led pin
    int led80 = 5;//led pin
    int ledsinal = 6;//led pin
    int buzzer = 7;//buzzer pin
    bool buzzing = false;
    uint32_t buzzTime;
    int incrementa = 8;//button pin
    //****************************************************************
    void setup()
    {
      Serial.begin(115200);
      gpsPort.begin(GPSBaud);
      pinMode(incrementa, INPUT);
      pinMode(led0, OUTPUT);  // declare LED as output
      pinMode(led20, OUTPUT);  // declare LED as output
      pinMode(led60, OUTPUT);  // declare LED as output
      pinMode(led80, OUTPUT);  // declare LED as output
      pinMode(ledsinal, OUTPUT);  // declare LED as output
      pinMode(buzzer, OUTPUT);  // dbuzeer
      delay(10);
    }

    void loop()
    {
      // Check the buttons
      val_inc = digitalRead(incrementa);  // read increment button
      if (val_inc == 1) {
       if (vel_prog > 80) {
          vel_prog = -20;
       }
          vel_prog = vel_prog + 20;
      }

      if (vel_prog == 0) {
        digitalWrite(led0,HIGH);
        digitalWrite(led20,LOW);
        digitalWrite(led60,LOW);
        digitalWrite(led80,LOW);
      } else if (vel_prog == 20) {
        digitalWrite(led0,LOW);
        digitalWrite(led20,HIGH);
        digitalWrite(led60,LOW);
        digitalWrite(led80,LOW);
      } else if (vel_prog == 60) {
        digitalWrite(led0,LOW);
        digitalWrite(led20,LOW);
        digitalWrite(led60,HIGH);
        digitalWrite(led80,LOW);
      } else if (vel_prog == 80) {
        digitalWrite(led0,LOW);
        digitalWrite(led20,LOW);
        digitalWrite(led60,LOW);
        digitalWrite(led80,HIGH);
      }

      // Check the GPS
      while (gps.available( gpsPort )) {
        gps_fix fix = gps.read();

        if (fix.valid.speed) {

          if ((fix.speed_kph() >= vel_prog) && (aux == 0)) { //comparacao da velocidades
            digitalWrite(ledsinal, HIGH);  // turn LED OFF
            tone(buzzer, 2200);
            aux = 1;
            buzzing = true;
            buzzTime = millis();
          }

          Serial.print( fix.speed_kph() );
        } else {
          Serial.print( '*' );
        }
      }

      // Check the buzzer
      if (buzzing && (millis() - buzzTime > 5000)) {
        digitalWrite(ledsinal, LOW);  // turn LED OFF
        noTone(buzzer);
        aux = 0; // Need this?
        buzzing = false;
      }
    }

Notice how it checks `millis()` every time through `loop` to see if the buzzer has been on for 5 seconds.  It doesn't *block* for 5 seconds.

It only checks the speed when a new GPS fix arrives.  This happens once per second, not every time through `loop`.

Your original version uses 11472 bytes of program space and 786 bytes of RAM.
The NeoGPS version uses 10722 bytes of program space and 590 bytes of RAM, a significant savings.

NeoGPS is smaller, faster and more accurate than all other libraries.  If you want to try it, NeoGPS is available from the Arduino IDE Library Manager, under the menu **Sketch -> Include Library -> Manage Libraries**.

The above sketch also uses my [NeoSWSerial](https://github.com/SlashDevin/NeoSWSerial).  It is much more efficient than SoftwareSerial.  SoftwareSerial blocks interrupts for long periods of time, which can interfere with other parts of your sketch.

It would be even better to use AltSoftSerial on pins 8 & 9 (on an UNO).


message:
NodeMCU does not boot up when GPIO pin is high

I have a NodeMCU board connected to a door and there is a micro switch that makes one GPIO pin (GPIO15 - D8 in this specific case) go high when the door opens.

My problem is if I lose power while the door is opened, the GPIO15 is fed high at the next boot when power is restored. And it makes the board go to a not responding state. I have to boot it again while the door is closed (pin is low) to bring it back to work. I experienced this while flashing too. I cannot flash while this pin is high (while the door is open).

How can I fix this?

body:
Certain pins of the ESP8266 perform special functions at bootup. GPIO15, when HIGH, makes the ESP8266 boot from an SD card.

You can read more about the special functions of the pins [here](http://www.forward.com.au/pfod/ESP8266/GPIOpins/index.html).

The solution? Don't use GPIO 0, 2 or 15 for things that can affect the boot sequence.


message:
Managing 2 ultrasonic sensors without blocking the other

I have an ultrasonic distance sensor. When this sensor is measuring a distance below 25 cm, a second sensor has to be measuring a distance below 5 cm. If not, there should be a one minute timespan, after which a speaker should make noise until the second sensor is measuring a distance below 5 cm.

I am having trouble with this. The first sensor has a lot of code it should be running as well, so using a while-loop to wait out one minute for the other sensor and creating noise after that isn't a possibility.

How do I go about this dilemma? I read into interrupts in Arduino but unfortunately I don't know how I'd make this work.

body:
fairly simple:

      if (time_is_up_for_sensor1()) read_sensor1(); //read sensor1 if time is up
      if (time_is_up_for_sensor2()) read_sensor2(); //read sensor2 if time is up

in time_is_up_for_sensor1/2(), update for the next round of reading:

    int time_is_up_for_sensor1(void) {
      static uint32_t millis_next = 0; //next millis
      if (millis() >= millis_next) {  //time is up for sensor1
        millis_next += INTERVAL_SENSOR1; //advance to the next measurement time
        return 1;  //needs to read sensor1
      } else return 0;
    }

similarly for sensor2


body:
I strongly advice you to use interrupts and make sure the sensors are in a cylindrical cone in order to prevent interference to each others as much as possible.

Here is code snippet which can give you an idea how the interrupts are set and used. I believe that you can adapt it to yours. It is from Arduino forum [(link)][1], credits to "cattledog".

    volatile unsigned long LastPulseTimeA;
    volatile unsigned long LastPulseTimeB;
    int durationA;
    int durationB;
    //unsigned long startTime;
    #define trigPinA 7
    #define echoPinA 2
    #define trigPinB 8
    #define echoPinB 3
    void setup() {
      Serial.begin (9600);
      pinMode(trigPinA, OUTPUT);
      pinMode(echoPinA, INPUT);
       pinMode(trigPinB, OUTPUT);
      pinMode(echoPinB, INPUT);
    attachInterrupt(digitalPinToInterrupt(echoPinA), EchoPinA_ISR, CHANGE);  // Pin 2 interrupt on any change
    attachInterrupt(digitalPinToInterrupt(echoPinB),EchoPinB_ISR, CHANGE);  // Pin3 interrupt on any change
    }
    void loop(){
      digitalWrite(trigPinA, LOW);
      digitalWrite(trigPinB, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPinA, HIGH);
      digitalWrite(trigPinB, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPinA, LOW);
      digitalWrite(trigPinB, LOW);
      Serial.print("Sensor A  ");
      Serial.print(LastPulseTimeA);
      Serial.print('\t');
      Serial.print((LastPulseTimeA/2) / 29.1,1);
      Serial.println("cm");
      Serial.print("Sensor B  ");
      Serial.print(LastPulseTimeB);
      Serial.print('\t');
      Serial.print((LastPulseTimeB/2) / 29.1,1);
      Serial.println("cm");

      delay(1000);
    }
    void EchoPinA_ISR() {
        static unsigned long startTimeA;

        if (digitalRead(echoPinA)) // Gone HIGH
            startTimeA = micros();
        else  // Gone LOW
            LastPulseTimeA = micros() - startTimeA;
    }
    void EchoPinB_ISR() {
        static unsigned long startTimeB;

        if (digitalRead(echoPinB)) // Gone HIGH
            startTimeB = micros();
        else  // Gone LOW
            LastPulseTimeB = micros() - startTimeB;
    }

  [1]: http://forum.arduino.cc/index.php?topic=275377.0


message:
How to change this function in to a non-blocking function?

How do I modify the getTheNumber() function to satisfy the statement below??
"
This function blocks until the user is done typing the number. Try to rewrite it in a non-blocking fashion. For example, it could return -1 on every call as long as the user is not done typing the number. On the first call after the user is done it would return the valid value. If you manage to write everything non-blocking, then you loop() will restart very often, and the program will work with no significant latency."

Here is the code:

    int getTheNumber()
    {
        char buffer[4];
        // Input up to 3 numbers until we find a * or #
        int i=0;
        while (1)
        {
            char key = keypad.getKey();

            // If it's a number AND we have space left, add to our string
            if ('0' <= key && key <= '9' && i < 3)
            {
                buffer[i] = key;
                i++;
            }
            // If it's a * or #, end
            else if ('#' == key && i > 0)
            {
                // Null terminate
                buffer[i] =0;
                int value = atoi(buffer);
                break;
            }
        }
        return atoi(buffer);
        }

body:
1. make buffer[] and i static.

2. get rid of the while() loop.

Like this:

    int getTheNumber()
    {
        static char buffer[4];
        static int i=0;
        // Input up to 3 numbers until we find a * or #
        char key = keypad.getKey();

        // If it's a number AND we have space left, add to our string
        if ('0' <= key && key <= '9' && i < 3)
            {
                buffer[i] = key;
                i++;
                return(-1)
            }
            // If it's a * or #, end
        else if ('#' == key && i > 0)
            {
                // Null terminate
                buffer[i] =0;
                int value = atoi(buffer);
                i=0;
                return atoi(buffer);
            }
    }


body:
I have a post about [doing serial input without blocking](http://www.gammon.com.au/serial).

Example code:

    /*
    Example of processing incoming serial data without blocking.

    Author:   Nick Gammon
    Date:     13 November 2011.
    Modified: 31 August 2013.

    Released for public use.
    */

    // how much serial data we expect before a newline
    const unsigned int MAX_INPUT = 50;

    void setup ()
      {
      Serial.begin (115200);
      } // end of setup

    // here to process incoming serial data after a terminator received
    void process_data (const char * data)
      {
      // for now just display it
      // (but you could compare it to some value, convert to an integer, etc.)
      Serial.println (data);
      }  // end of process_data

    void processIncomingByte (const byte inByte)
      {
      static char input_line [MAX_INPUT];
      static unsigned int input_pos = 0;

      switch (inByte)
        {

        case '\n':   // end of text
          input_line [input_pos] = 0;  // terminating null byte

          // terminator reached! process input_line here ...
          process_data (input_line);

          // reset buffer for next time
          input_pos = 0;
          break;

        case '\r':   // discard carriage return
          break;

        default:
          // keep adding if not full ... allow for terminating null byte
          if (input_pos < (MAX_INPUT - 1))
            input_line [input_pos++] = inByte;
          break;

        }  // end of switch

      } // end of processIncomingByte

    void loop()
      {
      // if serial data available, process it
      while (Serial.available () > 0)
        processIncomingByte (Serial.read ());

      // do other stuff here like testing digital input (button presses) ...

      }  // end of loop


message:
What are the unused pins in an Arduino L293D motor shield?

I want to connect the shield using wires instead of directly mounting on top of the Arduino board.

[![Arduino Motor Shield(L293D)][1]][1]

  [1]: https://i.stack.imgur.com/1VO49.jpg

body:
Check out this [Link][1]. Here, you can find this explanation in Code. I hope it will helpful for you.

    Pin usage with the Motorshield
    ---------------------------------------
    Analog pins: not used at all...
    A0 ... A5 are still available...
    They all can also be used as digital pins.
    Also, I2C (A4 = SDA and A5 = SCL) can be used.
    These pins have a breadboard area on the shield.
    Digital pins: used: 3,4,5,6,7,8,9,10,11,12
    Pin 9 and 10 are only used for the servo motors.
    Already in use: 0 (RX) and 1 (TX).
    Unused: 2,13
    Pin 2 has an soldering hole on the board, easy to connect a wire.
    Pin 13 is also connected to the system led.
    I2C is possible, but SPI is not possible since those pins are used.

  [1]: http://playground.arduino.cc/Main/AdafruitMotorShield


message:
Get when a button close the circuit

That seems to be a bit stupid to myself but I can't figure out to get to know when my button is pushed (closed) or released (open).

You must know that this not just a simple push button. Actually it is more of a complex button with multiples output (Y, G, 0V, COM, NO, NC, HORM, 12V).
With a multimeter i've been able to locale witch output are closed when the button is pressed. These are HORM (that is the name for two outputs -?!-) and on the other side COM and NO.

I've tried to plug that to my arduino Mega, on PIN 7, and getting the value with Digital.Read. Tho when i try to display it on the Serial, it doesn't work and return an error. (It did the same for HORM and COM/NO)

I also noticed something strange. When the button is pressed, Arduino seems to notice it because my "ON" led turns off and then turns back on. Like if the arduino was crashing. The 13th pin LED stay HIGH after the arduino goes back on.

Please, have a look at my code.

    int ledPin = 13; // choose the pin for the LED
    int inPin = 7;   // choose the input pin (for a pushbutton)
    int val = 0;     // variable for reading the pin status

    void setup() {
      Serial.begin(9600);
      pinMode(ledPin, OUTPUT);  // declare LED as output
      pinMode(inPin, INPUT);    // declare pushbutton as input
    }

    void loop(){
      val = digitalRead(inPin);  // read input value
      Serial.write(val);
      if (val == HIGH) {         // check if the input is HIGH (button released)
        digitalWrite(ledPin, LOW);  // turn LED OFF
      } else {
        digitalWrite(ledPin, HIGH);  // turn LED ON
      }

      delay(1000);
    }

Do you guys have any advice ?

Thank you very much in advance.

Also please have a look at the circuit. The only difference is that instead of having this kind of simple pushbutton, i've got my NO and COM plugged the same way.

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

  [1]: https://i.stack.imgur.com/BITSd.jpg

body:
Ok then.

I just tried that again and it simply seems that the wiring shown on the tutorial is not good at all.
I made another wiring that worked exactly fine.


message:
Matching the blink of an LED to midi music

I have a function that plays a song and lights an LED corresponding to the note that is being played. when the same note is played consecutively(i.e E in bar 6) instead of the LED turning on and off for each time the note is played the LED appears to remain lit. how do i get the LED to go no and off for these notes to better synchronize with the music being played? The delay of 414 is being used as quarter notes etc.

    void songlist (int song){
    if (song==1){
    songpage=1;
    playpage=0;
    mainpage=0;
    tonepage=0;
    lcd.clear();
    lcd.setCursor(4,0);
    lcd.print("ListeningTo:");// Print a message to the LCD.
    lcd.setCursor(1, 1);
    lcd.print(menuP1);
    //Plays Mary Had a Little Lamb
    //Bar 1
     noteOn(0x90, 0x40, 100); //Quarter note: E
    digitalWrite(LedR[3], HIGH);
    digitalWrite(LedC[1], LOW);
    delay(414);
    digitalWrite(LedR[3], LOW);
    digitalWrite(LedC[1], HIGH);
    noteOff(0x90, 0x40, 0);

    noteOn(0x90, 0x3E,100); //Quarter note: D
    digitalWrite(LedR[2], HIGH);
    digitalWrite(LedC[4], LOW);
    delay(414);
    digitalWrite(LedR[2], LOW);
    digitalWrite(LedC[4], HIGH);
    noteOff(0x90, 0x3E, 0);

    noteOn(0x90, 0x3C, 100); //Quarter note: C
    digitalWrite(LedR[2], HIGH);
    digitalWrite(LedC[2], LOW);
    delay(414);
    digitalWrite(LedR[2], LOW);
    digitalWrite(LedC[2], HIGH);
    noteOff(0x90, 0x3C, 0);

    noteOn(0x90, 0x3E, 100); //Quarter note: D
    digitalWrite(LedR[2], HIGH);
    digitalWrite(LedC[4], LOW);
    delay(414);
    digitalWrite(LedR[2], LOW);
    digitalWrite(LedC[4], HIGH);
    noteOff(0x90, 0x3E, 0);

    //Bar 2
    noteOn(0x90, 0x40, 100); //Quarter note: E
    digitalWrite(LedR[3], HIGH);
    digitalWrite(LedC[1], LOW);
    delay(414);
    digitalWrite(LedR[3], LOW);
    digitalWrite(LedC[1], HIGH);
    noteOff(0x90, 0x40, 0);

    noteOn(0x90, 0x40, 100); //Quarter note: E
    digitalWrite(LedR[3], HIGH);
    digitalWrite(LedC[1], LOW);
    delay(414);
    digitalWrite(LedR[3], LOW);
    digitalWrite(LedC[1], HIGH);
    noteOff(0x90, 0x40, 0);

    noteOn(0x90, 0x40, 100); //Half note: E
    digitalWrite(LedR[3], HIGH);
    digitalWrite(LedC[1], LOW);
    delay(828);
    digitalWrite(LedR[3], LOW);
    digitalWrite(LedC[1], HIGH);
    noteOff(0x90, 0x40, 0);

    //Bar 3
    noteOn(0x90, 0x3E, 100); //Quarter note: D
    digitalWrite(LedR[2], HIGH);
    digitalWrite(LedC[4], LOW);
    delay(414);
    digitalWrite(LedR[2], LOW);
    digitalWrite(LedC[4], HIGH);
    noteOff(0x90, 0x3E, 0);

    noteOn(0x90, 0x3E, 100); //Quarter note: D
    digitalWrite(LedR[2], HIGH);
    digitalWrite(LedC[4], LOW);
    delay(414);
    digitalWrite(LedR[2], LOW);
    digitalWrite(LedC[4], HIGH);
    noteOff(0x90, 0x3E, 0);

    noteOn(0x90, 0x3E, 100); //Half note: D
    digitalWrite(LedR[2], HIGH);
    digitalWrite(LedC[4], LOW);
    delay(828);
    digitalWrite(LedR[2], LOW);
    digitalWrite(LedC[4], HIGH);
    noteOff(0x90, 0x3E, 0);

    //Bar 4
    noteOn(0x90, 0x40, 100); //Quarter note: E
    digitalWrite(LedR[3], HIGH);
    digitalWrite(LedC[1], LOW);
    delay(414);
    digitalWrite(LedR[3], LOW);
    digitalWrite(LedC[1], HIGH);
    noteOff(0x90, 0x40, 0);

    noteOn(0x90, 0x43, 100); //Quarter note: G
    digitalWrite(LedR[3], HIGH);
    digitalWrite(LedC[4], LOW);
    delay(414);
    digitalWrite(LedR[3], LOW);
    digitalWrite(LedC[4], HIGH);
    noteOff(0x90, 0x43, 0);

    noteOn(0x90, 0x43, 100); //Half note: G
    digitalWrite(LedR[3], HIGH);
    digitalWrite(LedC[4], LOW);
    delay(828);
    digitalWrite(LedR[3], LOW);
    digitalWrite(LedC[4], HIGH);
    noteOff(0x90, 0x43, 0);

    //Bar5
    noteOn(0x90, 0x40, 100); //Quarter note: E
    digitalWrite(LedR[3], HIGH);
    digitalWrite(LedC[1], LOW);
    delay(414);
    digitalWrite(LedR[3], LOW);
    digitalWrite(LedC[1], HIGH);
    noteOff(0x90, 0x40, 0);

    noteOn(0x90, 0x3E, 100); //Quarter note: D
    digitalWrite(LedR[2], HIGH);
    digitalWrite(LedC[4], LOW);
    delay(414);
    digitalWrite(LedR[2], LOW);
    digitalWrite(LedC[4], HIGH);
    noteOff(0x90, 0x3E, 0);

    noteOn(0x90, 0x3C, 100); //Quarter note: C
    digitalWrite(LedR[2], HIGH);
    digitalWrite(LedC[2], LOW);
    delay(414);
    digitalWrite(LedR[2], LOW);
    digitalWrite(LedC[2], HIGH);
    noteOff(0x90, 0x3C, 0);

    noteOn(0x90, 0x3E, 100); //Quarter note: D
    digitalWrite(LedR[2], HIGH);
    digitalWrite(LedC[4], LOW);
    delay(414);
    digitalWrite(LedR[2], LOW);
    digitalWrite(LedC[4], HIGH);
    noteOff(0x90, 0x3E, 0);

    //Bar 6
    noteOn(0x90, 0x40, 100); //Quarter note: E
    digitalWrite(LedR[3], HIGH);
    digitalWrite(LedC[1], LOW);

    delay(414);
    digitalWrite(LedR[3], LOW);
    digitalWrite(LedC[1], HIGH);
    noteOff(0x90, 0x40, 0);

    noteOn(0x90, 0x40, 100); //Quarter note: E
    digitalWrite(LedR[3], LOW);
    digitalWrite(LedC[1], HIGH);

    delay(414);
    digitalWrite(LedR[3], LOW);
    digitalWrite(LedC[1], HIGH);
    noteOff(0x90, 0x40, 0);

    noteOn(0x90, 0x40, 100); //Quarter note: E
    digitalWrite(LedR[3], HIGH);
    digitalWrite(LedC[1], LOW);

    delay(414);
    digitalWrite(LedR[3], LOW);
    digitalWrite(LedC[1], HIGH);
    noteOff(0x90, 0x40, 0);

    noteOn(0x90, 0x40, 100); //Quarter note: E
    digitalWrite(LedR[3], HIGH);
    digitalWrite(LedC[1], LOW);

    delay(414);
    digitalWrite(LedR[3], LOW);
    digitalWrite(LedC[1], HIGH);
    noteOff(0x90, 0x40, 0);

    //Bar 7
    noteOn(0x90, 0x3E, 100); //Quarter note: D
    digitalWrite(LedR[2], HIGH);
    digitalWrite(LedC[4], LOW);
    delay(414);
    digitalWrite(LedR[2], LOW);
    digitalWrite(LedC[4], HIGH);
    noteOff(0x90, 0x3E, 0);

    noteOn(0x90, 0x3E, 100); //Quarter note: D
    digitalWrite(LedR[2], HIGH);
    digitalWrite(LedC[4], LOW);
    delay(414);
    digitalWrite(LedR[2], LOW);
    digitalWrite(LedC[4], HIGH);
    noteOff(0x90, 0x3E, 0);

    noteOn(0x90, 0x40, 100); //Quarter note: E
    digitalWrite(LedR[3], HIGH);
    digitalWrite(LedC[1], LOW);
    delay(414);
    digitalWrite(LedR[3], LOW);
    digitalWrite(LedC[1], HIGH);
    noteOff(0x90, 0x40, 0);

    noteOn(0x90, 0x3E, 100); //Quarter note: D
    digitalWrite(LedR[2], HIGH);
    digitalWrite(LedC[4], LOW);
    delay(414);
    digitalWrite(LedR[2], LOW);
    digitalWrite(LedC[4], HIGH);
    noteOff(0x90, 0x3E, 0);

    //Bar 8
    noteOn(0x90, 0x3C, 100); //Whole note: C
    digitalWrite(LedR[2], HIGH);
    digitalWrite(LedC[2], LOW);
    delay(1656);
    digitalWrite(LedR[2], LOW);
    digitalWrite(LedC[2], HIGH);
    noteOn(0x90, 0x3C, 0x00); //"Silent" note that makes sure the note stops playing.
    delay(2000);
    //End song
    }
    }

body:
First, write a helper function so that you do not have so much repeated code, and call it for each note:

    void playNote(int midi, int row, int col, int len)
    {
        noteOn(0x90, midi, 100);
        digitalWrite(LedR[row], HIGH);
        digitalWrite(LedC[col], LOW);
        delay(len);
        digitalWrite(LedR[row], LOW);
        digitalWrite(LedC[col], HIGH);
        noteOn(0x90, midi, 0x00);
    }

    ...
    //Bar 1
    playNote(0x40, 3, 1, 414); //Quarter note: E
    playNote(0x3e, 2, 4, 414); //Quarter note: D
    ...

Then, change it so that the note-off command and the LED switching can be done at different times:

    void playNote(int midi, int row, int col, int len, bool short_led = false)
    {
        int len1, len2;
        if (short_led) {
            len1 = len * 3 / 4;
            len2 = len * 1 / 4;
        } else {
            len1 = len;
            len2 = 0;
        }
        noteOn(0x90, midi, 100);
        digitalWrite(LedR[row], HIGH);
        digitalWrite(LedC[col], LOW);
        delay(len1);
        digitalWrite(LedR[row], LOW);
        digitalWrite(LedC[col], HIGH);
        delay(len2);
        noteOn(0x90, midi, 0x00);
    }


message:
Why is one part of my code being executed over the part before it?

The following code doesn't behave the way I would like it to. Inside the loop function im measuring the distance in front of the robot and if it is less than 15cm than the robot should move back and if it is less than 15cm on the left then move forward. When i run the program however only the left side is being checked and acted upon whilst the the if statement about the front and moving back is not doing anything. Something to note also is that when i swap the if statements and put the front checking ahead of the left checking it works but the left side is no longer being checked. Why is it that the if statement block in front is being executed over the previous one?

         void loop(){

         if(front.calculateDistance() < 15){
         MoveBack(200);
         }else{
          stopMoving();
         }

          if(left.calculateDistance() < 15){
         MoveForward(200);
         }else{
          stopMoving();
         }
       }

This is what the move methods do (move back and stopmoving just change input directions):

    void MoveForward(int rspeed) {
     // turn on motor A
     digitalWrite(in1, HIGH);
     digitalWrite(in2, LOW);
     analogWrite(enA, rspeed);
     // turn on motor B
     digitalWrite(in3, HIGH);
     digitalWrite(in4, LOW);
     analogWrite(enB, rspeed);
    }

body:
The problem is with your logic. You are saying:

1. If it's too close in front then move backwards
2. Otherwise stop all movement
3. If it's too close on the left then move forwards
4. **Otherwise stop all movement**.

That means that if it's too close in front, but not too close on the left, then it will think about moving backwards, but then immediately stop because it's not too close on the left.

You need to think more about the whole space at once, not just one individual direction. For instance, what do you do if it's too close in front *and* too close on the left? At the moment you'll crash into whatever is in front.

So you should be thinking about four conditions:

1. Too close in front AND too close on the left
2. Too close in front BUT NOT too close on the left
3. NOT too close in front BUT too close on the left
4. NOT too close in front AND NOT too close on the left.

Then you can choose the right action to perform.

If your specific setup means that it can never be too close in front at the same time as being too close on the left you can collapse it into a simpler form:

1. **IF** it's too close in front then move backwards
2. **ELSE IF** it's too close on the left then move forwards
3. **ELSE** stop all movement.


message:
Moving cursor on LCD and changing highlighted value

I have the code shown below. The goal is to change the value of hours, minutes or seconds based on where the cursor is placed.

    #include <Adafruit_RGBLCDShield.h>
    #include <utility/Adafruit_MCP23017.h>
    Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

    void setup() {
      lcd.begin(16, 2); //format of display
    }

    void loop() {
        int hours = 11;
        int minutes = 11;
        int seconds = 11;
        lcd.setCursor(0,0);
        lcd.print(hours);
        lcd.print(":");
        lcd.print(minutes);
        lcd.print(":");
        lcd.print(seconds);
        lcd.noBlink();
        delay(300);
        lcd.blink();
        delay(300);

        if (buttons & BUTTON_RIGHT) {
          move cursor right;
          if(lcd.setCursor == lcd.setCursor(0,3) {
            minutes += 1 }

    }

I though of a way to do this. I would have three variables and print each of these out with a default value. With the use of the buttons, the user should be able to move the blinking cursor to hours, minutes or seconds, and increase or decrease the value of the variable.

I would do this by seeing what location the cursor is at. For example, if the cursor was on minutes, I would write something like `if(lcd.setCursor == lcd.setCursor(0,3) or lcd.setCursor == lcd.setCursor(0,4)) { minutes += 1}.`

Of course these functions don't exist, so I am wondering what I can do to move a cursor and check its position.

Thanks in advance

body:
Firstly, you should set the time variables outside the main loop (as a global variable). If you put them in the main loop, the time would always reset to *11:11:11* after 0.6s of delay.

> lcd.setCursor == lcd.setCursor(0,3)

I dont think you can do this (unless the function returns you with the location of the cursor, have to check the header file of the library).

Instead, you should keep track of the location of the cursor with another variable (as mentioned by *gre_gor*), say *int curLoc*. But note that you have to keep track of the range of values it can go. (*0 < curLoc < 16*)

To summarise, the code could look like this:

    #include <Adafruit_RGBLCDShield.h>
    #include <utility/Adafruit_MCP23017.h>
    Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

    int hours = 11;
    int minutes = 11;
    int seconds = 11;

    int curLoc = 0; //Current cursor location (x-axis)

    void setup() {
      lcd.begin(16, 2); //format of display
    }

    void loop() {
      lcd.setCursor(0,0);
      lcd.print(hours);
      lcd.print(":");
      lcd.print(minutes);
      lcd.print(":");
      lcd.print(seconds);
      lcd.noBlink();
      delay(300);
      lcd.blink();
      delay(300);

      //move cursor right;
      if (buttons & BUTTON_RIGHT) {
        //Keep the tracker in range
        if(curLoc >= 0 && curLoc < 16){
        curLoc += 1;
        }

        if(curLoc == 3)
        {
          minutes += 1
         }

    }


message:
How to control low power devices when implementing Low Power Mode strategy?

As part of implementing Low Power Mode, I wish to control power to attached devices, such as the HC12 transmitter/receiver.  I've read of the usage of MOSFETs to control motors and lighting systems, but don't understand the applicability of such implementations to control something like an HC12, which consumes approximately 200ma.
Should I be using MOSFET and, if so which one?  Else, what is a better solution?  The circuit I am now working on is essentially a PRO Micro, an HC12, and a small led, though I will later add a camera module, approx. 100ma.

body:
Yes, MOSFETs are what you want.

The temptation is to just insert any old logic-level N-channel MOSFET in the ground connection to the device like you would when driving a relay, etc. However that method is fraught with danger. You get such issues as ground-level offsets (where ground isn't actually ground but some mV above ground) which can result in logic level mismatch problems. You get the possibility of power trying to make its way to ground through the device's IO pins and your MCU, etc.

So it is best to instead use a P-channel MOSFET to switch the positive power rail to the device. If the voltage you are switching is the same as the voltage you are doing the switching with (i.e., you are switching 5V using a 5V-level GPIO pin such as on an Arduino) then that is really all you need. However if the voltage you want to switch is higher then you will need to switch the P-channel MOSFET with an N-channel MOSFET, or an NPN BJT.

Here's two schemes:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/pAm3M.png)

<!-- End schematic -->

In the left schematic M1 is kept off by R2, and pulling the control GPIO low it turns M1 on allowing the current to flow.

In the right schematic M1 is kept off by R2 in the same way, but M2, when turned on by the GPIO being driven HIGH. R3 keeps M2 off while the MCU is not ready to drive the GPIO pin yet (in the bootloader, etc).

One thing to remember when switching the power off on either schematic is to first set all the GPIO pins that communicate directly with the device to INPUT mode. That will prevent them trying to power the target device through the IO pins (which will typically have ESD diodes that would feed current to Vcc).

All MOSFETs should be logic level (except M1 in the right schematic which can have a higher threshold depending on the voltage you are switching - best to keep it all logic level though as a rule).


message:
CRC test fail on MS5803-14BA pressure sensor - what can I do?

**Problem:**

I bought two MS5803-14BA sensors and I soldered them myself to a SOIC-8 PCB to be able to use them. Only one sensor is used in my circuit. To access it, I use an Arduino Pro Mini 8MHz/3.3V with a library that has a CRC check for the sensor. When assembled to the circuit, one of the sensors pass the test, however the other fails. I'm using I2C to access the sensor.

I would like both sensors to pass the test so I could compare readings from two assembled circuits, but I really don't know how to do it. I have a three questions:

 - Where this problem can be originating from?
 - What kind of limitations I have for not passing the CRC test? Does it mean that the collected data can not be trusted?
 - If I use the raw readings D1 and D2 from a sensor that have failed the CRC test and pos-compensate them in the computer, will I have trustful results?
 - How to solve it?

**Schematic:**

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/e5TNO.png)

<!-- End schematic -->

 - The resistors R1 and R2 are pull-up resistors.
 - The capacitor C1 is recommended by the sensor's datasheet.
 - Sensor's PS pin is connected to Vcc in order to select I2C mode for communication. The other option was SDI.
 - Sensor's CLS pin is connected to ground to select the address 0x77 to the sensor. Case it is connected to Vcc, the address is set to 0x76.

**Documentation**

 - [Sensor's Data Sheet][1]
 - [Library used][2]

  [1]: http://www.te.com/commerce/DocumentDelivery/DDEController?Action=showdoc&DocId=Data SheetMS5803-14BABpdfEnglishENG_DS_MS5803-14BA_B.pdfCAT-BLPS0013
  [2]: https://github.com/millerlp/MS5803_14
  [3]: http://lukemiller.org/index.php/2014/04/arduino-code-for-ms5803-pressure-sensors/

body:
### Where this problem can be originating from?

As per page 7 and page 14 of the data sheet, there are 16 bytes of PROM in the unit which contain calibration information determined and written at the factory. This calibration information includes coefficients that must be used by whatever's reading the sensor to adjust for manufacturing variations. The data also include a [CRC check code](https://en.wikipedia.org/wiki/Cyclic_redundancy_check) to let you confirm you've read the PROM correctly.

So there are three possibilities here:

1. The CRC as written to PROM is wrong.
2. There was an error while transferring the data from PROM to your MCU.
3. The software is doing the CRC calculation incorrectly.

The [source code](https://github.com/millerlp/MS5803_14/blob/master/MS5803_14.cpp#L131-L132) suggests that the most likely reason for this sort of failure is faulty wiring between the MCU and the sensor.

### What kind of limitations I have for not passing the CRC test? Does it mean that the collected data can not be trusted?

Potentially, yes. To determine how bad things really are and what might be going wrong you need to do a bit more experimentation.

When you call the `initializeMS_5803()` function you pass it a boolean parameter determining whether it's running in verbose mode. Set this to true so it prints out the coefficients 0 through 7 to the serial port during initialization. Restart your Arduino several times, ideally under different conditions of temperature, power, physical wire configuration (if any), etc., and see if the values ever change. If they are ever different from a previous run, you have either cabling corrupting the data transfer or a defective sensor. You may be able to look at which bits change, if any change consistently, to get some insight into how "random" the problem really is. (Could it be that only a certain bit pattern is being transmitted unreliably?)

If all values always read the same, compare them to the values read from your good sensor. If they're quite similar, and you're generally getting similar readings under similar conditions from both sensors, I would suspect possibility 1 or 3 above, and reckon that you're likely to be getting reasonably reliable data from the sensor. If the values are vastly different this doesn't necessarily mean that the sensor will be unreliable; I have no idea how much these coefficients vary from unit to unit.

### If I use the raw readings D1 and D2 from a sensor that have failed the CRC test and pos-compensate them in the computer, will I have trustful results?

Again, that depends on whether or not it looks as if you're getting corruption on the data link. As above, if you ever read different PROM data from run to run on startup, the sensor is much less likely to be producing trustworthy data.

You could also try comparing the raw readings from both sensors under conditions as close to identical as you can make them. I don't know how close in calibration the two sensors are, but if they are close, the raw data should look similar and that would be a sign of reliability.

### How to solve it?

First, determine if you are getting the same or different PROM values across multiple startups. If they're always the same, send your good and bad values to the author of the driver and ask him if he thinks his CRC algorithm might have an error in it. (Or check it yourself against the application note mentioned in the data sheet, if you feel up to it.)

If the CRC algorithm in the software you're using is correct, given that you appear to reading successfully from another sensor, I'd send the sensor giving the CRC error back to the manufacturer, along with the coefficients you had read, with a query as to whether they have got the CRC wrong or you're reading the data wrong.

If you're getting different PROM values, that's either a faulty sensor or a wiring problem. You may be able to help isolate this with the usual tricks: slow down the transfer speed (with `Wire.setClock()`) to see if that reduces data corruption, re-wire the circuit with different (and preferably shorter) wires and other parts, make sure you've got caps in the appropriate places to filter noise, put a scope or a logic analyzer on the SCK and SDA lines to see if you can see any dodgy-looking waveforms, and so on. If anything looks strange, you can always use your working unit for comparison. If all that still looks good, it may well be a faulty sensor.


message:
Program crashes when I use Serial.println()?

I'm working with a fuzzy logic controller with Arduino, I'm trying to emulate an AC by entering inputs [temperature and humidity] using two potentiometers and the output is the AC power.

This is the basic part of the program, every thing is good, I can print the values of Temp and HU. But when I try to print the value of the Power, nothing happens, and the serial monitor displays nothing. By trial and error, I can see that `Serial.println` with power or any variable related to power crashes the program. What may be the reason?

        void loop()
    {
        // Read Input: Temperature
        ttemp = analogRead(temp);

        Serial.println("the analoge Tempreture is ");
        Serial.println (ttemp);

        ttemp = map(ttemp, 0, 1023, 5, 65);
        ttemp = constrain(ttemp, 5, 65);

        Serial.println("the actual Tempreture is ");
        Serial.println (ttemp);
        Serial.println("-------------------------");
        delay(100);

        g_fisInput[0] = ttemp;

        // Read Input: Humidity
        hhu = analogRead(hu);
        Serial.println("the analoge Humidity is ");
        Serial.println (hhu);

        hhu = map(hhu, 0, 1023, 16, 100);
        hhu = constrain(hhu, 16, 100);

        Serial.println("the actual Humidity is ");
        Serial.println (hhu);
        Serial.println("-----------------------");
        delay(100);
        g_fisInput[1] = hhu;

        g_fisOutput[0] = 0;

        fis_evaluate();

        // Set output vlaue: Power
        int ppower1 = g_fisOutput[0];
       // Serial.println("the actual Power is ");
       // Serial.println (ppower1);
        ppower = map(ppower1,100,3000,0,255);
        ppower = constrain (ppower, 0,255);
        analogWrite(power , ppower);

       // Serial.println("the analoge Tempreture is ");
        //Serial.println (ppower);
       // Serial.println("--------------------------");

    }

body:
You should have provided your full Arduino code. Without setup() part of Arduino code, we can not exactly tell what might be wrong. Please provide it and I'll revise my answer as well.

Check if you have this code in your setup() function:

    Serial.begin(9600);

9600 is baud rate and it could be any other supported baud rate(you can see those by opening a Serial monitor and clicking on 9600 baud rate on bottom right edge).

Related to to comments above, from experience and it can be easily "counted", RAM shouldn't be a problem in such short code.