text:
communicating esp 32 with arduino uno
I made a spider robot using arduino and from esp. I made an audio output device which is linked to python program which writes a particular data (when we speak a command) to esp board and accordingly the voice would be activated. Now I want to link them together.
If the esp32 sends a particular data the function in arduino is executed.  Therefore I want to connect esp32 to arduino uno though Serial monitor and send data from esp 32 to arduino. I have only analog pins vacant as all digital pins are used for the servos. how can I achieve this?.
In the main arduino file there are 2 more flexitimer and flexitimer2.cpp files but there is no need of editing them and hence I am giving the code of main file.
    #include <Servo.h>    //to define and control servos
    #include "FlexiTimer2.h"//to set a timer to manage all servos
    /* Servos --------------------------------------------------------------------*/
    //define 12 servos for 4 legs
    char data = 0;
    Servo servo[4][3];
    //define servos' ports
    const int servo_pin[4][3] = { {2, 3, 4}, {5, 6, 7}, {8, 9, 10}, {11, 12, 13} };
    /* Size of the robot ---------------------------------------------------------*/
    const float length_a = 55;
    const float length_b = 77.5;
    const float length_c = 27.5;
    const float length_side = 71;
    const float z_absolute = -28;
    /* Constants for movement ----------------------------------------------------*/
    const float z_default = -50, z_up = -30, z_boot = z_absolute;
    const float x_default = 62, x_offset = 0;
    const float y_start = 0, y_step = 40;
    const float y_default = x_default;
    /* variables for movement ----------------------------------------------------*/
    volatile float site_now[4][3];    //real-time coordinates of the end of each leg
    volatile float site_expect[4][3]; //expected coordinates of the end of each leg
    float temp_speed[4][3];   //each axis' speed, needs to be recalculated before each movement
    float move_speed;     //movement speed
    float speed_multiple = 1; //movement speed multiple
    const float spot_turn_speed = 4;
    const float leg_move_speed = 8;
    const float body_move_speed = 3;
    const float stand_seat_speed = 1;
    volatile int rest_counter;      //+1/0.02s, for automatic rest
    //functions' parameter
    const float KEEP = 255;
    //define PI for calculation
    const float pi = 3.1415926;
    /* Constants for turn --------------------------------------------------------*/
    //temp length
    const float temp_a = sqrt(pow(2 * x_default + length_side, 2) + pow(y_step, 2));
    const float temp_b = 2 * (y_start + y_step) + length_side;
    const float temp_c = sqrt(pow(2 * x_default + length_side, 2) + pow(2 * y_start + y_step + length_side, 2));
    const float temp_alpha = acos((pow(temp_a, 2) + pow(temp_b, 2) - pow(temp_c, 2)) / 2 / temp_a / temp_b);
    //site for turn
    const float turn_x1 = (temp_a - length_side) / 2;
    const float turn_y1 = y_start + y_step / 2;
    const float turn_x0 = turn_x1 - temp_b * cos(temp_alpha);
    const float turn_y0 = temp_b * sin(temp_alpha) - turn_y1 - length_side;
    /* ---------------------------------------------------------------------------*/

      - setup function
       ---------------------------------------------------------------------------*/
    void setup()
    {
      //start serial for debug
      Serial.begin(9600);
      Serial.println("Robot starts initialization");

      //initialize default parameter
      pinMode(14, OUTPUT);
      set_site(0, x_default - x_offset, y_start + y_step, z_boot);
      set_site(1, x_default - x_offset, y_start + y_step, z_boot);
      set_site(2, x_default + x_offset, y_start, z_boot);
      set_site(3, x_default + x_offset, y_start, z_boot);
      for (int i = 0; i < 4; i++)
      {
        for (int j = 0; j < 3; j++)
        {
          site_now[i][j] = site_expect[i][j];
        }
      }
      //start servo service
      FlexiTimer2::set(20, servo_service);
      FlexiTimer2::start();
      Serial.println("Servo service started");
      //initialize servos
      servo_attach();
      Serial.println("Servos initialized");
      Serial.println("Robot initialization Complete");
    //   stand();
    //   delay(1000);
    //   hand_shake(2);
    //   Serial.println("hihihihihi");
    //   delay(1000);
    //   step_forward();
    //   step_forward();
    //   step_forward();
    //   step_forward();
    //   step_forward();
    //   step_forward();
    //   delay(1000);
    //   step_back();
    //   step_back();
    //   step_back();
    //   step_back();
    //   step_back();
    //   step_back();
    //   delay(1000);

    //   turn_left();
    //   turn_left();
    //   turn_left();
    //   turn_left();
    //   delay(1000);
    //   turn_right();
    //   turn_right();
    //   turn_right();
    //   turn_right();
    //   delay(1000);
    //   hand_wave(4);
    //   delay(1000);
    //   hand_shake(4);
    //   delay(1000);
    //   sit();
    //   delay(1000);
    }

    void servo_attach(void)
    {
      for (int i = 0; i < 4; i++)
      {
        for (int j = 0; j < 3; j++)
        {
          servo[i][j].attach(servo_pin[i][j]);
          delay(100);
        }
      }
    }

    void servo_detach(void)
    {
      for (int i = 0; i < 4; i++)
      {
        for (int j = 0; j < 3; j++)
        {
          servo[i][j].detach();
          delay(100);
        }
      }
    }

    /*
      - loop function
       ---------------------------------------------------------------------------*/
    void loop()
    {

      if(Serial.available() > 0)
       {
          data = Serial.read();
          Serial.print(data);
          Serial.print("\n");

          if(data == 'F')
            {
             Serial.println("Step forward");
             step_forward();
            }
          else if(data == 'B')
             {
              Serial.println("Step back");
              step_back();
            }
          else if(data == 'L')
             {
             Serial.println("Turn left");
             turn_left();

            }
          else if(data == 'R')
            {
              Serial.println("Turn right");
              turn_right();

            }
            else if(data == 'X')
            {
             Serial.println("Stand");
             stand();
            }
             else if(data == 'x')
            {
              Serial.println("Sit");
              sit();
            }
           else if(data == 'S' ||data == 'D' )

            {

            }

             else if(data == 'W')
            {
              digitalWrite(14, HIGH);
            }
              else if(data == 'w')
            {
             digitalWrite(14, LOW);
            }
            else if(data == 'V')
            {
              Serial.println("Hand wave");
              hand_wave(3);
            }
              else if(data == 'v')
            {
             Serial.println("Hand wave");
             hand_shake(3);
            }
             else if(data == 'U')
            {
              Serial.println("Body dance");
              body_dance(10);
            }
              else if(data == 'u')
            {
              Serial.println("Body dance");
              body_dance(10);
            }
            while(Serial.available()) {Serial.read();}
       }

    }

    /*
      - sit
      - blocking function
       ---------------------------------------------------------------------------*/
    /*
      - spot turn to right
      - blocking function
      - parameter step steps wanted to turn
       ---------------------------------------------------------------------------*/
    void turn_right()
    {
        move_speed = spot_turn_speed;

        if (site_now[2][1] == y_start)
        {
          //leg 2&0 move
          set_site(2, x_default + x_offset, y_start, z_up);
          wait_all_reach();

          set_site(0, turn_x0 - x_offset, turn_y0, z_default);
          set_site(1, turn_x1 - x_offset, turn_y1, z_default);
          set_site(2, turn_x0 + x_offset, turn_y0, z_up);
          set_site(3, turn_x1 + x_offset, turn_y1, z_default);
          wait_all_reach();

          set_site(2, turn_x0 + x_offset, turn_y0, z_default);
          wait_all_reach();

          set_site(0, turn_x0 + x_offset, turn_y0, z_default);
          set_site(1, turn_x1 + x_offset, turn_y1, z_default);
          set_site(2, turn_x0 - x_offset, turn_y0, z_default);
          set_site(3, turn_x1 - x_offset, turn_y1, z_default);
          wait_all_reach();

          set_site(0, turn_x0 + x_offset, turn_y0, z_up);
          wait_all_reach();

          set_site(0, x_default + x_offset, y_start, z_up);
          set_site(1, x_default + x_offset, y_start, z_default);
          set_site(2, x_default - x_offset, y_start + y_step, z_default);
          set_site(3, x_default - x_offset, y_start + y_step, z_default);
          wait_all_reach();

          set_site(0, x_default + x_offset, y_start, z_default);
          wait_all_reach();
        }
        else
        {
          //leg 1&3 move
          set_site(1, x_default + x_offset, y_start, z_up);
          wait_all_reach();

          set_site(0, turn_x1 + x_offset, turn_y1, z_default);
          set_site(1, turn_x0 + x_offset, turn_y0, z_up);
          set_site(2, turn_x1 - x_offset, turn_y1, z_default);
          set_site(3, turn_x0 - x_offset, turn_y0, z_default);
          wait_all_reach();

          set_site(1, turn_x0 + x_offset, turn_y0, z_default);
          wait_all_reach();

          set_site(0, turn_x1 - x_offset, turn_y1, z_default);
          set_site(1, turn_x0 - x_offset, turn_y0, z_default);
          set_site(2, turn_x1 + x_offset, turn_y1, z_default);
          set_site(3, turn_x0 + x_offset, turn_y0, z_default);
          wait_all_reach();

          set_site(3, turn_x0 + x_offset, turn_y0, z_up);
          wait_all_reach();

          set_site(0, x_default - x_offset, y_start + y_step, z_default);
          set_site(1, x_default - x_offset, y_start + y_step, z_default);
          set_site(2, x_default + x_offset, y_start, z_default);
          set_site(3, x_default + x_offset, y_start, z_up);
          wait_all_reach();

          set_site(3, x_default + x_offset, y_start, z_default);
          wait_all_reach();
        }
    }

    /*
      - go forward
      - blocking function
      - parameter step steps wanted to go
       ---------------------------------------------------------------------------*/
    void step_forward()
    {
        move_speed = leg_move_speed;

        if (site_now[2][1] == y_start)
        {
          //leg 2&1 move
          set_site(2, x_default + x_offset, y_start, z_up);
          wait_all_reach();
          set_site(2, x_default + x_offset, y_start + 2 * y_step, z_up);
          wait_all_reach();
          set_site(2, x_default + x_offset, y_start + 2 * y_step, z_default);
          wait_all_reach();

          move_speed = body_move_speed;

          set_site(0, x_default + x_offset, y_start, z_default);
          set_site(1, x_default + x_offset, y_start + 2 * y_step, z_default);
          set_site(2, x_default - x_offset, y_start + y_step, z_default);
          set_site(3, x_default - x_offset, y_start + y_step, z_default);
          wait_all_reach();

          move_speed = leg_move_speed;

          set_site(1, x_default + x_offset, y_start + 2 * y_step, z_up);
          wait_all_reach();
          set_site(1, x_default + x_offset, y_start, z_up);
          wait_all_reach();
          set_site(1, x_default + x_offset, y_start, z_default);
          wait_all_reach();
        }
        else
        {
          //leg 0&3 move
          set_site(0, x_default + x_offset, y_start, z_up);
          wait_all_reach();
          set_site(0, x_default + x_offset, y_start + 2 * y_step, z_up);
          wait_all_reach();
          set_site(0, x_default + x_offset, y_start + 2 * y_step, z_default);
          wait_all_reach();

          move_speed = body_move_speed;

          set_site(0, x_default - x_offset, y_start + y_step, z_default);
          set_site(1, x_default - x_offset, y_start + y_step, z_default);
          set_site(2, x_default + x_offset, y_start, z_default);
          set_site(3, x_default + x_offset, y_start + 2 * y_step, z_default);
          wait_all_reach();

          move_speed = leg_move_speed;

          set_site(3, x_default + x_offset, y_start + 2 * y_step, z_up);
          wait_all_reach();
          set_site(3, x_default + x_offset, y_start, z_up);
          wait_all_reach();
          set_site(3, x_default + x_offset, y_start, z_default);
          wait_all_reach();
        }
    }

    /*
      - go back
      - blocking function
      - parameter step steps wanted to go
       ---------------------------------------------------------------------------*/
    void step_back()
    {
        move_speed = leg_move_speed;
        if (site_now[3][1] == y_start)
        {
          //leg 3&0 move
          set_site(3, x_default + x_offset, y_start, z_up);
          wait_all_reach();
          set_site(3, x_default + x_offset, y_start + 2 * y_step, z_up);
          wait_all_reach();
          set_site(3, x_default + x_offset, y_start + 2 * y_step, z_default);
          wait_all_reach();

          move_speed = body_move_speed;

          set_site(0, x_default + x_offset, y_start + 2 * y_step, z_default);
          set_site(1, x_default + x_offset, y_start, z_default);
          set_site(2, x_default - x_offset, y_start + y_step, z_default);
          set_site(3, x_default - x_offset, y_start + y_step, z_default);
          wait_all_reach();

          move_speed = leg_move_speed;

          set_site(0, x_default + x_offset, y_start + 2 * y_step, z_up);
          wait_all_reach();
          set_site(0, x_default + x_offset, y_start, z_up);
          wait_all_reach();
          set_site(0, x_default + x_offset, y_start, z_default);
          wait_all_reach();
        }
        else
        {
          //leg 1&2 move
          set_site(1, x_default + x_offset, y_start, z_up);
          wait_all_reach();
          set_site(1, x_default + x_offset, y_start + 2 * y_step, z_up);
          wait_all_reach();
          set_site(1, x_default + x_offset, y_start + 2 * y_step, z_default);
          wait_all_reach();

          move_speed = body_move_speed;

          set_site(0, x_default - x_offset, y_start + y_step, z_default);
          set_site(1, x_default - x_offset, y_start + y_step, z_default);
          set_site(2, x_default + x_offset, y_start + 2 * y_step, z_default);
          set_site(3, x_default + x_offset, y_start, z_default);
          wait_all_reach();

          move_speed = leg_move_speed;

          set_site(2, x_default + x_offset, y_start + 2 * y_step, z_up);
          wait_all_reach();
          set_site(2, x_default + x_offset, y_start, z_up);
          wait_all_reach();
          set_site(2, x_default + x_offset, y_start, z_default);
          wait_all_reach();
        }
    }

    // add by RegisHsu

    void body_left(int i)
    {
      set_site(0, site_now[0][0] + i, KEEP, KEEP);
      set_site(1, site_now[1][0] + i, KEEP, KEEP);
      set_site(2, site_now[2][0] - i, KEEP, KEEP);
      set_site(3, site_now[3][0] - i, KEEP, KEEP);
      wait_all_reach();
    }

    void body_right(int i)
    {
      set_site(0, site_now[0][0] - i, KEEP, KEEP);
      set_site(1, site_now[1][0] - i, KEEP, KEEP);
      set_site(2, site_now[2][0] + i, KEEP, KEEP);
      set_site(3, site_now[3][0] + i, KEEP, KEEP);
      wait_all_reach();
    }

    void hand_wave(int i)
    {
      float x_tmp;
      float y_tmp;
      float z_tmp;
      move_speed = 1;
      if (site_now[3][1] == y_start)
      {
        body_right(15);
        x_tmp = site_now[2][0];
        y_tmp = site_now[2][1];
        z_tmp = site_now[2][2];
        move_speed = body_move_speed;
        for (int j = 0; j < i; j++)
        {
          set_site(2, turn_x1, turn_y1, 50);
          wait_all_reach();
          set_site(2, turn_x0, turn_y0, 50);
          wait_all_reach();
        }
        set_site(2, x_tmp, y_tmp, z_tmp);
        wait_all_reach();
        move_speed = 1;
        body_left(15);
      }
      else
      {
        body_left(15);
        x_tmp = site_now[0][0];
        y_tmp = site_now[0][1];
        z_tmp = site_now[0][2];
        move_speed = body_move_speed;
        for (int j = 0; j < i; j++)
        {
          set_site(0, turn_x1, turn_y1, 50);
          wait_all_reach();
          set_site(0, turn_x0, turn_y0, 50);
          wait_all_reach();
        }
        set_site(0, x_tmp, y_tmp, z_tmp);
        wait_all_reach();
        move_speed = 1;
        body_right(15);
      }
    }

    void hand_shake(int i)
    {
      float x_tmp;
      float y_tmp;
      float z_tmp;
      move_speed = 1;
      if (site_now[3][1] == y_start)
      {
        body_right(15);
        x_tmp = site_now[2][0];
        y_tmp = site_now[2][1];
        z_tmp = site_now[2][2];
        move_speed = body_move_speed;
        for (int j = 0; j < i; j++)
        {
          set_site(2, x_default - 30, y_start + 2 * y_step, 55);
          wait_all_reach();
          set_site(2, x_default - 30, y_start + 2 * y_step, 10);
          wait_all_reach();
        }
        set_site(2, x_tmp, y_tmp, z_tmp);
        wait_all_reach();
        move_speed = 1;
        body_left(15);
      }
      else
      {
        body_left(15);
        x_tmp = site_now[0][0];
        y_tmp = site_now[0][1];
        z_tmp = site_now[0][2];
        move_speed = body_move_speed;
        for (int j = 0; j < i; j++)
        {
          set_site(0, x_default - 30, y_start + 2 * y_step, 55);
          wait_all_reach();
          set_site(0, x_default - 30, y_start + 2 * y_step, 10);
          wait_all_reach();
        }
        set_site(0, x_tmp, y_tmp, z_tmp);
        wait_all_reach();
        move_speed = 1;
        body_right(15);
      }
    }

    void head_up(int i)
    {
      set_site(0, KEEP, KEEP, site_now[0][2] - i);
      set_site(1, KEEP, KEEP, site_now[1][2] + i);
      set_site(2, KEEP, KEEP, site_now[2][2] - i);
      set_site(3, KEEP, KEEP, site_now[3][2] + i);
      wait_all_reach();
    }

    void head_down(int i)
    {
      set_site(0, KEEP, KEEP, site_now[0][2] + i);
      set_site(1, KEEP, KEEP, site_now[1][2] - i);
      set_site(2, KEEP, KEEP, site_now[2][2] + i);
      set_site(3, KEEP, KEEP, site_now[3][2] - i);
      wait_all_reach();
    }

    void body_dance(int i)
    {
      float x_tmp;
      float y_tmp;
      float z_tmp;
      float body_dance_speed = 2;
      sit();
      move_speed = 1;
      set_site(0, x_default, y_default, KEEP);
      set_site(1, x_default, y_default, KEEP);
      set_site(2, x_default, y_default, KEEP);
      set_site(3, x_default, y_default, KEEP);
      wait_all_reach();
      //stand();
      set_site(0, x_default, y_default, z_default - 20);
      set_site(1, x_default, y_default, z_default - 20);
      set_site(2, x_default, y_default, z_default - 20);
      set_site(3, x_default, y_default, z_default - 20);
      wait_all_reach();
      move_speed = body_dance_speed;
      head_up(30);
      for (int j = 0; j < i; j++)
      {
        if (j > i / 4)
          move_speed = body_dance_speed * 2;
        if (j > i / 2)
          move_speed = body_dance_speed * 3;
        set_site(0, KEEP, y_default - 20, KEEP);
        set_site(1, KEEP, y_default + 20, KEEP);
        set_site(2, KEEP, y_default - 20, KEEP);
        set_site(3, KEEP, y_default + 20, KEEP);
        wait_all_reach();
        set_site(0, KEEP, y_default + 20, KEEP);
        set_site(1, KEEP, y_default - 20, KEEP);
        set_site(2, KEEP, y_default + 20, KEEP);
        set_site(3, KEEP, y_default - 20, KEEP);
        wait_all_reach();
      }
      move_speed = body_dance_speed;
      head_down(30);
    }

    /*
      - microservos service /timer interrupt function/50Hz
      - when set site expected,this function move the end point to it in a straight line
      - temp_speed[4][3] should be set before set expect site,it make sure the end point
       move in a straight line,and decide move speed.
       ---------------------------------------------------------------------------*/
    void servo_service(void)
    {
      sei();
      static float alpha, beta, gamma;

      for (int i = 0; i < 4; i++)
      {
        for (int j = 0; j < 3; j++)
        {
          if (abs(site_now[i][j] - site_expect[i][j]) >= abs(temp_speed[i][j]))
            site_now[i][j] += temp_speed[i][j];
          else
            site_now[i][j] = site_expect[i][j];
        }

        cartesian_to_polar(alpha, beta, gamma, site_now[i][0], site_now[i][1], site_now[i][2]);
        polar_to_servo(i, alpha, beta, gamma);
      }

      rest_counter++;
    }

    /*
      - set one of end points' expect site
      - this founction will set temp_speed[4][3] at same time
      - non - blocking function
       ---------------------------------------------------------------------------*/
    void set_site(int leg, float x, float y, float z)
    {
      float length_x = 0, length_y = 0, length_z = 0;

      if (x != KEEP)
        length_x = x - site_now[leg][0];
      if (y != KEEP)
        length_y = y - site_now[leg][1];
      if (z != KEEP)
        length_z = z - site_now[leg][2];

      float length = sqrt(pow(length_x, 2) + pow(length_y, 2) + pow(length_z, 2));

      temp_speed[leg][0] = length_x / length * move_speed * speed_multiple;
      temp_speed[leg][1] = length_y / length * move_speed * speed_multiple;
      temp_speed[leg][2] = length_z / length * move_speed * speed_multiple;

      if (x != KEEP)
        site_expect[leg][0] = x;
      if (y != KEEP)
        site_expect[leg][1] = y;
      if (z != KEEP)
        site_expect[leg][2] = z;
    }

    /*
      - wait one of end points move to expect site
      - blocking function
       ---------------------------------------------------------------------------*/
    void wait_reach(int leg)
    {
      while (1)
        if (site_now[leg][0] == site_expect[leg][0])
          if (site_now[leg][1] == site_expect[leg][1])
            if (site_now[leg][2] == site_expect[leg][2])
              break;
    }

    /*
      - wait all of end points move to expect site
      - blocking function
       ---------------------------------------------------------------------------*/
    void wait_all_reach(void)
    {
      for (int i = 0; i < 4; i++)
        wait_reach(i);
    }

    /*
      - trans site from cartesian to polar
      - mathematical model 2/2
       ---------------------------------------------------------------------------*/
    void cartesian_to_polar(volatile float &alpha, volatile float &beta, volatile float &gamma, volatile float x, volatile float y, volatile float z)
    {
      //calculate w-z degree
      float v, w;
      w = (x >= 0 ? 1 : -1) * (sqrt(pow(x, 2) + pow(y, 2)));
      v = w - length_c;
      alpha = atan2(z, v) + acos((pow(length_a, 2) - pow(length_b, 2) + pow(v, 2) + pow(z, 2)) / 2 / length_a / sqrt(pow(v, 2) + pow(z, 2)));
      beta = acos((pow(length_a, 2) + pow(length_b, 2) - pow(v, 2) - pow(z, 2)) / 2 / length_a / length_b);
      //calculate x-y-z degree
      gamma = (w >= 0) ? atan2(y, x) : atan2(-y, -x);
      //trans degree pi->180
      alpha = alpha / pi * 180;
      beta = beta / pi * 180;
      gamma = gamma / pi * 180;
    }

    /*
      - trans site from polar to microservos
      - mathematical model map to fact
      - the errors saved in eeprom will be add
       ---------------------------------------------------------------------------*/
    void polar_to_servo(int leg, float alpha, float beta, float gamma)
    {
      if (leg == 0)
      {
        alpha = 90 - alpha;
        beta = beta;
        gamma += 90;
      }
      else if (leg == 1)
      {
        alpha += 90;
        beta = 180 - beta;
        gamma = 90 - gamma;
      }
      else if (leg == 2)
      {
        alpha += 90;
        beta = 180 - beta;
        gamma = 90 - gamma;
      }
      else if (leg == 3)
      {
        alpha = 90 - alpha;
        beta = beta;
        gamma += 90;
      }

      servo[leg][0].write(alpha);
      servo[leg][1].write(beta);
      servo[leg][2].write(gamma);
    }

NOTE: I am deleting some functions like void sit(void) stand as the maximum limit of characters was reached.
This is my esp32 code
    #include "Arduino.h"
    #include "WiFi.h"
    #include "Audio.h"

    #define I2S_DOUT      25
    #define I2S_BCLK      27
    #define I2S_LRC       26

    Audio audio;

    char data = 0;
    void setup()
    {

      Serial.begin(115200);

      WiFi.disconnect();
      WiFi.mode(WIFI_STA);
      WiFi.begin( "Physics", "299792458");

      while (WiFi.status() != WL_CONNECTED)
        delay(1500);

      audio.setPinout(I2S_BCLK, I2S_LRC, I2S_DOUT);
      audio.setVolume(100);
      audio.connecttospeech("Hello From akshit singh,,welcome to tapovan international school's project day ,,i am a smart walking robot ,you can also call me astra bot ", "en");

    }

    void loop(){
    if(Serial.available() > 0)
       {
          data = Serial.read();
          Serial.print(data);
          if(data == 'A')
            {
             audio.connecttospeech("hello everyone ,welcome to tapovan international school's project day ", "en");
             Serial.println("done");
            }

          else if(data == 'B')
            {
             audio.connecttospeech("BYE Bye everyone", "hi");
             Serial.println("done 2");
            }
          else if(data == 'C')
            {
             audio.connecttospeech("i am a smart walking robot ,you can also call me astra bot ", "hi");
             Serial.println("done 2");
            }

          else if(data == 'F')
            {
             audio.connecttospeech("going forward ,sir", "hi");
             Serial.println("done 2");
            }

          else if(data == 'b')
            {
             audio.connecttospeech("going backward ,sir", "hi");
             Serial.println("done 2");

            }
          else if(data == 'L')
            {
             audio.connecttospeech("moving left, sir", "hi");
             Serial.println("done 2");

            }
          else if(data == 'R')
            {
             audio.connecttospeech("moving right ,sir", "hi");
             Serial.println("done 2");

            }

       }

    {
      audio.loop();
    }

      }

    void audio_info(const char *info) {
      Serial.print("audio_info: "); Serial.println(info);
    }

Well first of all you need to be aware that the UNO runs at 5V, and the ESP32 at 3V3, so you will need a level shifter in between the UNO and ESP32 unless you want to possibly damage your ESP32.
You can create a bidirectional level shifter with an N-Channel mosfet and 2 resistors,
or buy a breakout board, or use a chip like the GTL2010. Just note that not all bidirectional level shifters are the same, some require changing the direction with a pin(usually DIR), the GTL2010 is not one of those.
Bitbanged UART
Can be done on any pin.
Either a uni or bi directional level shifter will work just fine.
SPI
Since your servos aren't being run by PWM/Timer hardware you could use the analog pins for a couple of your servos, and use the SPI peripheral which uses pins 10, 11, 12, and 13.
Your ESP32 is sending the commands, so you'd want to set up the ESP32 as the master, and the UNO as the slave.
Just like the BBUART option, either a uni or bi directional level shifter will work.
I2C
This uses the SDA and SCL pins next to VREF, which are really just A4 and A5. And again, you'd set the ESP32 to be the master, and the UNO to be the slave.
Be aware that you will need a bidirectional level shifter, a unidirectional will not work.
Although I don't recommend, there is a chance you may be able to get away without using a level shifter by attaching your pull-up resistors to 3V3. Just note, for the atmega328P to register a high logic level, the input voltage needs to be 60% of VCC. So if its running at 5V, it will take 3V to read high, which does have a chance at working. But if its running at 5V5, it will require 3V3 to register high and probably wont function properly if at all.
Another reason to use a level shifter is apparently the Arduino I2C library uses the internal pull-up resistors, so you would have to modify the library to disable them, so your ESP32 pins aren't pulled to 5V.
BBUART is probably your best bet, it uses the least pins, and easiest to work with in code. All you need is a level shifter and you're good to go. But if you feel confident enough coding wise, you could try I2C without a level shifter, and if it doesn't work then purchase one.


text:
Can't read data from registers using I2C
I am trying to read data from the registers 6, 7, 8 and 9 of the STC3100 (Data Sheet) using an arduino uno.
I followed this tutorial: https://howtomechatronics.com/tutorials/arduino/how-i2c-communication-works-and-how-to-use-it-with-arduino/ And adjusted the device and register adress accordingly.
This isn't working and instead of returning the data on the register I'm just getting 16 over and over again.
Here is my code:
#include <Wire.h>
int ADXLAddress = 0x70;

#define X_Axis_Register_DATAX0 0x08

#define X_Axis_Register_DATAX1 0x09

#define Power_Register 0x00

int X0,X1,X_out;

void setup() {

  Wire.begin();

  Serial.begin(9600);
  delay(100);
  Wire.beginTransmission(ADXLAddress);
  Wire.write(Power_Register);
  Wire.write(16);
  Wire.endTransmission();
}
void loop() {
  delay(2000);
  Wire.beginTransmission(ADXLAddress);

  Wire.write(X_Axis_Register_DATAX0);
  Wire.write(X_Axis_Register_DATAX1);

  Wire.endTransmission();

  Wire.requestFrom(ADXLAddress,2);

  if(Wire.available()<=2) {
    X0 = Wire.read();
    X1 = Wire.read();
  }

  Serial.print("X0= ");
  Serial.print(X0, BIN);
  Serial.print("   X1= ");
  Serial.println(X1, BIN);
}

Please include your code into your question (by editing it)

I'm not sure, but from reading the data sheet I would expect, that only one Register address must be written, than read the two bytes; the register address will be auto incremented, it seems. You code writes register adress 8, then 9 and I would say, you start reading from reg address 9 then auto increment to 10 (9=battery Voltage High reg 10 = Temperature low reg). The data sheet could also be interpreted as writing more than one register address without reading data, is not specified.

The following code shows, how I would read from a STC3100. But I own none of them, so I can not try the code. I would be very surprised if it works directly. Use it as an example. Perhaps we could improve it together. ;-)
#include <Wire.h>

#define STC_ADDRESS 0x70
#define MODE_REGISTER 0x00
#define CURRENT_LOW_REGISTER 0x06
#define VOLTAGE_LOW_REGISTER 0x08

int voltage, current;
int high_value = 0;

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

  Wire.begin();
  delay(100);
  // power on the STC
  Wire.beginTransmission(STC_ADDRESS);
  Wire.write(MODE_REGISTER);
  Wire.write(16);
  Wire.endTransmission();
}

void loop()
{
  Wire.beginTransmission(STC_ADDRESS);
  Wire.write(VOLTAGE_LOW_REGISTER);
  Wire.requestFrom(STC_ADDRESS, 2);
  delay(500);
  if( Wire.available() > 0 )
  {
    voltage = Wire.read();
    //Serial.print("REG 8 = ");
    //Serial.println(voltage);
  }
  delay(500);
  if( Wire.available() > 0 )
  {
    high_value = Wire.read();
    //Serial.print("REG 9 = ");
    //Serial.println(high_value);
    voltage += (high_value << 8);
    //Serial.print("voltage = ");
    //Serial.println(voltage);

  }
  Wire.endTransmission();

  Wire.beginTransmission(STC_ADDRESS);
  Wire.write(CURRENT_LOW_REGISTER);
  Wire.requestFrom(STC_ADDRESS, 2);
  delay(500);
  if( Wire.available() > 0 )
  {
    current = Wire.read();
    //Serial.print("REG 6 = ");
    //Serial.println(current);
  }
  delay(500);
  if( Wire.available() > 0 )
  {
    high_value = Wire.read();
    //Serial.print("REG 7 = ");
    //Serial.println(high_value);
    current += (high_value << 8);
    //Serial.print("current = ");
    //Serial.println(current);
  }
  Wire.endTransmission();

  Serial.print("V= ");
  Serial.print(voltage);
  Serial.print("   C= ");
  Serial.println(current);
}

I tried the code you posted and currently it won't print anything if I run the whole code. If I run it so that it only reads registers 8 and 9, it will print a value (which is incorrect) once and then stop, as if it isn't looping at all.

I looked over the code and found some errors. I changed the code with the fixed version. I made an error with the first #define macro that should have prevented the code from compiling. How did you compile it? Have you fixed the macro? If there is no hardware error, this version should at least read the registers. I have included some ''Serial.println` you can uncomment, to see the raw register values. If it will stop again, you can see where.

Seems to be working well at the moment. Thank you so much for your help :)

source: Stack Exchange

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

sort: votes


text:
Is there a way to upload precompiled code to an arduino?
My company is developing a programmable remote control car which is driven by an Arduino Nano. We would like a way for the user to install software updates to the Arduino, but we don't want to give the user access to the code.
Is there a way to compile Arduino code without automatically uploading it, so that I can put the pre-compiled binary up for download on a website?
Then after this how would I go about manually uploading it (to the Arduino)?

There are similar questions to this one. Certainly it can be done.

i developed avrdude based exe, try it, http://iot.6te.net/ardiuno.php

Is there a way to compile arduino code without automatically uploading it, so that I can put the pre-compiled binary up for download on a website?

Yes, you can save the .hex file produced by the compiler. If you turn on verbose output from the compiler you can find the temporary directory where it is stored. Simply copy from there to a folder for download on the website.

And then after this how would I go about manually uploading it (To the arduino)?

You can do that with the command line tool avrdude but as that is somewhat complex with a lot of parameters it might be easier to use a graphical front-end. One such tool is xloader. There are several. This depends on your end-users and the host machine that they will be using.
You can find some more info here.
Cheers!

That said, I would like add, that if you can put hex file on website for users to download and flash the Arduino with it, then I (or anybody else) can also make a hex file and flash it to the arduino.

I think if you do not publish the source code, the project will be a little bit unconstructive, both for developers and users, especially when it is based in open hardware.
You can put hex files available to users, but also the source code, allowing the community to participate in the development of your product.
Anyway, if you use third-party code in your project, such as libraries, remember to respect their licenses.
Best regards. Good luck with the project.

I actually agree with you, and I would like to just make everything open source. But my boss has other plans

@TheIronKnuckle If you are using any libraries (even Arduino's libraries (the Arduino language)) then make sure you are not violating any of those licences either.

@TheIronKnuckle Your boss must pay you a salary. That is the whole point.

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

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


text:
Can I reassign my Arduino Uno COM Port?
The Arduino SW, under Tools, identifies my Uno as COM Port 3. However, COM Port 3 on my computer is in use by a chip set. My computer assigned COM Port 4 to my Arduino Uno.
Can I reassign my Uno to COM Port 4?
Edit: This question also applies to people who don't have administrative privileges. They do not have privileges to change the port via Windows Device Manager.

If the Arduino IDE identified your Uno as COM Port 3, your computer most likely has already assigned COM Port 3 to your Uno. You can double check the port assignment in Device manager > Ports.

The issue is that I am not an admin and do not have the ability to re-assign ports on the computer. Therefore, I would like to Re-assign the port that Arduino is requesting. It can't be that hard.

This is not an answer. You can reassign the com port via the device manager... Assuming you are on a Windows PC

You can change your COM Port number for a device by following these instructions:
http://plugable.com/2011/07/04/how-to-change-the-com-port-for-a-usb-serial-adapter-on-windows-7

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


text:
Arduino IDE Visual Studio and compile problems blank project .ino hack
I'm new to Arduino and have little programming experience apart from my computer science degree.  I used C++ for some projects in my degree but am barely proficient.
My first project is relatively complex process control for an Arduino beginner and I've quickly become frustrated with the Arduino IDE which seems to be a common problem.  I've installed Visual Studio with the Visual Micro plugin (Win7) but I'm getting compile problems.  I have successfully built a data logging sensor array both in Arduino IDE and Visual Studio in Win7, but as I'm trying to add complexity I'm experiencing difficulties.
I found this recommendation on Gammon Forum for use with the Arduino IDE to achieve a standard C++ build environment but it's not working in the visual studio environment.
Files contained in "EmptySketch" project folder:
"EmptySketch.ino"
//beginning EmptySketch.ino
//end EmptySketch.ino

"TestSketch.cpp"
//beginning TestSketch.cpp

#include <Arduino.h>

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("Hello");
  Serial.flush();
}

void loop() {
  // put your main code here, to run repeatedly:
}
//end TestSketch.cpp

When I create a project in Arduino IDE this compiles, uploads and runs with the expected output, but when I open EmptySketch.ino in VS it builds, uploads but gives no output.
Can anyone help me with this approach or should I simply upload my real project using a conventional .ino which won't compile and ask for help with that?

Firstly, please format your code correctly. Edit the question, highlight all code and press CTRL + K. Secondly, if you upload a blank sketch, what do you actually expect to happen?

Maybe, instead of a complex first project, slowly work through the examples in the Arduino Cookbook, or some other such literature, in order to familiarise yourself with the code and coding environment. The Arduino IDE is an extremely simplified environment, but even so, it  still takes some getting used to. However, I'm sure after a few examples you will be up and running...


text:
Field Programming a Arduino with another Arduino with SD card over RX/TX lines
I am not sure if this question has been asked before but here's what I wanted to do.
I have a Arduino Nano, which I need to update with a new sketch. The plan is to be able to use another Arduino (maybe a Nano again), with an SD card reader and a sketch loaded as HEX file on it. Then connect both using a 4 pin RX/TX/5V/GND and upload the sketch from the transmitter to the receiver. Is it possible?
I am not sure how to do this; I know I can use one Arduino as an ISP to update other, but I am thinking of streaming the hex file to the other. Has anyone done this, any hints would be extremely helpful.

You can find some great info here: http://forum.arduino.cc/index.php?topic=351358.0 and http://www.gammon.com.au/forum/?id=11638

There's actually a library for that as well! See here and here.

See What happens when code is uploaded using the bootloader?
There is a graphic on that page (reproduced below) which shows the general idea of what happens when you program using Tx/Rx after reset.

You could delve into the specs for the STK500 protocol (see linked page) and make your second Arduino follow that, to program from the SD card file.


text:
Unable to upload sketch after bootloader has been flashed on Arduino Micro
I have created my own custom Arduino Micro, but I am experiencing problems when I attempt to upload an sketch via USB in Arduino IDE.
Here is how I program the Arduino Micro:
avrdude  -c atmelice_isp  -p m32u4 -P usb -u -v -e -U flash:w:Caterina-Micro.hex

And the result:
$ avrdude  -c atmelice_isp  -p m32u4 -P usb -v -e -U flash:w:Caterina-Micro.hex
avrdude: Version 6.1, compiled on Mar 23 2014 at 04:42:55
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/usr/local/Cellar/avrdude/6.1/etc/avrdude.conf"
         User configuration file is "/Users/aUser/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : usb
         Using Programmer              : atmelice_isp
avrdude: usbdev_open(): Found Atmel-ICE CMSIS-DAP, serno: J41800023270
avrdude: Found CMSIS-DAP compliant device, using EDBG protocol
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : JTAG3_ISP
         Description     : Atmel-ICE (ARM/AVR) in ISP mode
         Vtarget         : 4.9 V
         SCK period      : 125.00 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x1e9587
avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as D8
avrdude: safemode: efuse reads as CB
avrdude: erasing chip
avrdude: reading input file "Caterina-Micro.hex"
avrdude: input file Caterina-Micro.hex auto detected as Intel Hex
avrdude: writing flash (32730 bytes):

Writing | ################################################## | 100% 38.80s

avrdude: 32730 bytes of flash written
avrdude: verifying flash memory against Caterina-Micro.hex:
avrdude: load data flash data from input file Caterina-Micro.hex:
avrdude: input file Caterina-Micro.hex auto detected as Intel Hex
avrdude: input file Caterina-Micro.hex contains 32730 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 133.93s

avrdude: verifying ...
avrdude: 32730 bytes of flash verified

avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as D8
avrdude: safemode: efuse reads as CB
avrdude: safemode: Fuses OK (E:CB, H:D8, L:FF)

avrdude done.  Thank you.

The error in Arduino IDE when flashing sketch via USB:
Sketch uses 23.994 bytes (83%) of program storage space. Maximum is 28.672 bytes.
Global variables use 1.145 bytes (44%) of dynamic memory, leaving 1.415 bytes for local variables. Maximum is 2.560 bytes.
Forcing reset using 1200bps open/close on port /dev/tty.usbmodem1411
PORTS {/dev/cu.Bluetooth-Incoming-Port, /dev/cu.Bluetooth-Modem, /dev/cu.usbmodem1411, /dev/tty.Bluetooth-Incoming-Port, /dev/tty.Bluetooth-Modem, /dev/tty.usbmodem1411, } / {/dev/cu.Bluetooth-Incoming-Port, /dev/cu.Bluetooth-Modem, /dev/cu.usbmodem1411, /dev/tty.Bluetooth-Incoming-Port, /dev/tty.Bluetooth-Modem, /dev/tty.usbmodem1411, } => {}
PORTS {/dev/cu.Bluetooth-Incoming-Port, /dev/cu.Bluetooth-Modem, /dev/cu.usbmodem1411, /dev/tty.Bluetooth-Incoming-Port, /dev/tty.Bluetooth-Modem, /dev/tty.usbmodem1411, } / {/dev/cu.Bluetooth-Incoming-Port, /dev/cu.Bluetooth-Modem, /dev/cu.usbmodem1411, /dev/tty.Bluetooth-Incoming-Port, /dev/tty.Bluetooth-Modem, /dev/tty.usbmodem1411, } => {}
Uploading using selected port: /dev/tty.usbmodem1411
/Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/bin/avrdude -C/Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -P/dev/tty.usbmodem1411 -b57600 -D -Uflash:w:/var/folders/64/6n0yv9515hz1n6z3bdzcwv6h0000gn/T/build2162381950044145986.tmp/IMUNode.cpp.hex:i

avrdude: Version 6.0.1, compiled on Apr  3 2014 at 22:00:33
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/Users/aUser/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/tty.usbmodem1411
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Your problem is that your board doesn't have the bootloader loaded into the chip.
You have success with the ATMEL-ICE ISP because it is an in-system programmer (ISP) and you are downloading the code directly into the chip.
When you use the USB, I see from your output that the programmer is "butterfly" and the description indicates AVR109. These both indicate that the program is trying to be loaded through a bootloader.
A bootloader is a bit of code that resides in the codespace section of flash. It allows you to send the program through the UART. The bootloader then saves it to the codespace section of flash such that both the bootloader and your program co-exist.
To fix this, use the Arduino IDE along with your ATMEL-ICE ISP to load the bootloader into the microcontroller. This can be done by going into Tools and then Burn Bootloader (of course with the correct programmer selected).
This will then allow you to download your code through the Arduino IDE.
PS. You can program your sketch straight to your Arduino using your ATMEL-ICE ISP without downloading the bootloader. Do this by selecting the Upload Using Programmer option in the menus.

This is not correct. I received this same error after using the Arduino IDE to burn the bootloader, which the IDE said it did successfully.

@Cerin there could be many things that it could be such as the wrong bootloader or a problem with the USB circuitry or even your Tx pin has died. https://arduino.stackexchange.com/q/13292/19409


text:
I can not upload hex files outside of the Arduino IDE to my Pro Micro
I have a strange problem. I am trying to upload a .hex file to my lovely Arduino Pro Micro, but am unable to do so. If I use the Arduino IDE, it goes through perfectly fine and uploads the sketch. However, if I try to use avrdude from the terminal I get:
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: programmer did not respond to command: leave prog mode
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: programmer did not respond to command: exit bootloader

My commandline is:
avrdude -patmega32u4 -cavr109 -P/dev/ttyACM0 -t

and the full output is:
Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
Found programmer: Id = ""; type =
    Software Version = .; Hardware Version = .
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
Found programmer: Id = ""; type =
Software Version = .; Hardware Version = .
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude: butterfly_recv(): programmer is not responding
    avrdude: error: programmer did not respond to command: leave prog mode
    avrdude: butterfly_recv(): programmer is not responding
    avrdude: error: programmer did not respond to command: exit bootloader

Thank you for any help, it is greatly appreciated.
--Dominic

The programmer is wrong. You don't have avr109 bootloader, enable verbose upload from the IDE and copy-paste the command it used.

That is what I did. Also, the chip on my Arduino says "MEGA32u4" right on it...

Oops, I read it as Pro Mini not as Pro Micro.

Unlike the 328P and similar boards the 32U4 has no hardware method for triggering a reset to enter the bootloader.
On the boards with a UART -> USB interface the USB interface chip manually toggles the RESET pin to activate the bootloader. Without that chip a reset can't be done.
So a different method had to be invented. That method involves opening the serial port at 1200 baud and immediately closing it. That triggers a reboot into the bootloader.
The Arduino IDE manually performs that task when you press the upload button. It is not something that avrdude knows how to do.
So you will have to come up with some method of opening the serial port at 1200 baud immediately before running avrdude. Of course, it means the serial interface device disappears for a short while whilst the chip reboots and enters the bootloader, so you need to ensure you have a delay between the reset method and the call to avrdude - a delay that is long enough for your OS to redetect the chip, yet not so long that the bootloader times out.

Excellent! Thank you. I reset the board manually to test it, and I was able to upload my hex file normally.

I had this bizarre problem with my Leonardo and Uno boards. I was even using Arduino IDE (v1.8.5) to upload the code. In some extreme circumstances, one of the boards was not even listed under serial ports (Tools->Port)
After many attempts I simply burned bootloader using another Uno, and that solved the issue!
It is still unclear to me what happened but the issue was caused by an RFID card reader using SPI (ICSP pinouts on the board). The card reader (PN532) was sending data to Arduino when either I was uploading the code or the board was booting up.
UPDATE Jan 2020
After time and many attempts, I realised that Arduino UNO should not be accessed via ISP interface during code upload. The module PN532 was randomly massaging UNO when I flushed the microcontroller which corrupted the code.

What bootloader and what version(s)? There are several bootloaders. Can you elaborate? Did you use the official ones? Or Optiboot?

@PeterMortensen, I don't remember what bootloader was the most recent in 2017 but that was for sure the official version at that time available in Arduino IDE.


text:
Making an automated watering system with Arduino
I am trying to make an automated watering system using an Arduino.
Here is my wiring diagram:

And here is my circuit wired up:

Here is the code that I'm using with Arduino. The code seems alright and the wiring on the Arduino seems okay as well, but I don't know where to place a speaker on the Arduino. The biggest problem is that the program doesn't run like I coded. After I uploaded this code to Arduino, the water pump just keeps running forever. Can anyone check up my code to make this run properly?
/**automated watering program **/

#include <avr/sleep.h>
#include <avr/wdt.h>
#define BEAT 300 // define time for the tone.
#define PINNO 12

int led = 13;

void setup() {
  // setup code to run once:
  pinMode(led, OUTPUT);
}

void loop() {
  // main code here, to run repeatedly:
  tone(PINNO,262,BEAT); // C(do)
  delay(BEAT);
  tone(PINNO,294,BEAT); // D(re)
  delay(BEAT);
  tone(PINNO,330,BEAT); // E(mi)
  delay(BEAT);
  tone(PINNO,262,BEAT); // C (do)
  delay(BEAT);
  tone(PINNO,294,BEAT); // D(re)
  delay(BEAT);
  tone(PINNO,330,BEAT); // E(mi)
  delay(BEAT);
  tone(PINNO,392,BEAT); // G(so)
  delay(BEAT);
  tone(PINNO,330,BEAT); // E(mi)
  delay(BEAT);
  tone(PINNO,294,BEAT); // D(re)
  delay(BEAT);
  tone(PINNO,262,BEAT); // C(do)
  delay(BEAT);
  tone(PINNO,294,BEAT); // D(re)
  delay(BEAT);
  tone(PINNO,330,BEAT); // E(mi)
  delay(BEAT);
  tone(PINNO,294,BEAT); // D(re)
  delay(BEAT);
  delay(1000); // Wait for 1 second
  digitalWrite(led,HIGH); //Make No. 11pin output HIGH = 5V
  delay(500); // Watering time
  digitalWrite(led,LOW); //Make No.11 pin output LOW = 0V
  // Shut down program to save battery using by watchdogtimer 24h standby mode
  int var = 0;
  while(var < 10800) {
    delayWDT(9); // 9seconds of shutdown
    var++; // 10800times repeat ＝24h
  }
}

void delayWDT(unsigned long t) {
  // delay excute while using powerdown mode
  delayWDT_setup(t); // watchdog timer setting
  ADCSRA &= ~(1 << ADEN); // ADEN bit clear and stop ADC
  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // Powerdow mode
  sleep_enable();
  sleep_mode(); // sleep mode
  sleep_disable(); // WatchDog Timer times up and start working again
  ADCSRA |= (1 << ADEN); // turn on the ADC
}

void delayWDT_setup(unsigned int ii) {
  // setting up timer
  // 0=16ms, 1=32ms, 2=64ms, 3=128ms, 4=250ms, 5=500ms
  // 6=1sec, 7=2sec, 8=4sec, 9=8sec
  byte bb;
  if (ii > 9 ) {
    // get rid of strange numbers
    ii = 9;
  }
  bb =ii & 7;
  if (ii > 7) {
    bb |= (1 << 5);
  }
  bb |= ( 1 << WDCE );
  MCUSR &= ~(1 << WDRF); // MCU Status Reg. Watchdog Reset  Flag ->0
  // start timed sequence
  WDTCSR |= (1 << WDCE) | (1<<WDE); // allow to edit watchdog
  // set new watchdog timeout value
  WDTCSR = bb;
  WDTCSR |= _BV(WDIE);
}
ISR(WDT_vect) {
  // the work after time up, WDT
  //  wdt_cycle++;
}

Maybe if you try controlling pin 11, where the pump is connected, and not pin 13, it may help. Also I can't understand your wiring there (but it looks wrong - there are components missing). Please provide a schematic (which you can do using the schematic editor available when you edit your question).

As for where to place a speaker - how about pin 12, like you have already decided in your code?

Thank you, I uploaded a diagram i wire them exactly like the diagram.

What model transistor is that?

it says BC5478, It came with Arduino Starter Kit.

also it was not speaker, it was Piezo. I don't know where to place it.

I'm missing a resistor between the arduino and the transistor. Also missing a (flyback) diode on the motor.

Problems with your setup:

Your pump is connected to pin 11 but you are controlling pin 13 (int led = 13;)
You have an LED in line with your transistor base. That should be a resistor, and the LED should be in parallel with the base (with its own resistor).
Your transistor is wired wrong. According to the datasheet the pins are C-B-E as viewed from the angle in your wiring diagram. You have the Arduino connected to E instead of B, the pump connected to B instead of C, and ground connected to C instead of E.
You don't have a flyback diode across the motor.

simulate this circuit – Schematic created using CircuitLab

Why does it need the resistors ??

i tired this but didnt work

this time, speaker worked but the pump didnt work

authors: Олтиной Божаева


text:
Arduino compiler uploading last saved version of sketch, not current
Is this an issue or a defined behavior? I am using Arduino IDE 1.6.6
Sometimes I made changes in code, and immediately upload them to the Arduino board. And many times issues already fixed are persisting, leaving me that feeling of "the uploaded code has not the changes I have just made". Then I save my sketch, compile and upload again and the issue vanishes. As long as the issue get someway fixed, I tend to forgot about it.
As software engineer, most of the times I assume the code I am compiling and uploading / publishing to any platform is always the latest, not the latest saved. I believe this is not the behavior of the Arduino IDE. It uploads the last saved version of code, not the last modified.
In summary: I believe the Arduino IDE uploads to the board the last saved version of the sketch, not the current one being modified. Can anyone confirm this?
Thanks in advance.

I can't confirm that since I use an external editor, which necessitates saving before compiling.  I sometimes use a menu which I wave the mouse over to compile+upload.  ¶  See the last post or two in topic #46983 in forum.arduino.cc which depending on interpretation may or may not suggest that in 2010 it did not work as you say.

I can't prove it (i.e., I haven't looked at the code), but it seems to me that 1.6.6 saves before uploading – seems worth a test. Also worth mentioning the platform where you're seeing this behavior. I'm on a MacBook Pro running OS X 10.11.2.

Yeah, the option is on. I am on Windows 10. If it's working correctly, then I probably had some issue with the upload, or simply believing I uploaded the last version when actually didn't. I would like to discard as much clues as possible, I hate this kind of "magic" fixes. Thank for your replies!

If you were not using an external editor, it would be the latest, whether it is saved or not.  In that case, just use Ctrl-S before the Ctrl-U when uploading.  It will save it and upload it.  If an external editor, do the Ctrl-S there, then Ctrl-U in the IDE.  Don't trust the auto-save option when using an external editor.

I haven't tried it but it would be an easy experiment to make on some throw-away code.
However, do note that saving before compiling or uploading is optional in the Arduino IDE. That may very well be the key to what you observed. I keep mine enabled, i.e., to save before any compile or upload. The option is in the Preferences dialog accessed from the menus, not in the manually-edited preferences.txt file. That might be the key to what you observed.
Update:
In that case, including the pre-defined macros __DATE__ and __TIME__ (of the pre-processor run) and __TIMESTAMP__ (of the file's last modification) in a "Hello" string can help debug this.
These pages list the standard, and common predefined macros implemented in gcc's pre-processor.
Note also that most version control systems offer similar macros that get replaced at checkout to embed a revision number and other version-control information.

Thanks for your reply. Apparently I have the option to save when compiling or uploading on, but I still face some "outdated code" like issues. They got fixed after save, compile and upload. I am guessing now that I may had an upload error. Or not uploading at all. But I would like to discard as most clues as possible. Apparently, the IDE is saving my files as expected... (assuming there is no open bugs on that feature).

In the general sense things like __TIME__ may not fairly depict the compilation flow as these would not cause the editor aspect of the IDE to report that there have been any program changes to invalidate a cached compilation.  For example with a traditional Makefile setup timestamps like this don't work unless something else forces a rebuild of the code where they appear.  So this isn't really a good test; making a trivial change for example to a printed string would be.


text:
Arduino Nano Update failure - avrdude: stk500_recv(): programmer is not responding
Before I tear all my hair and teeth out, can anyone please help. I have tried googling an answer and have not found anything.
My Setup:

Win7 64bit
Arduino 1.6.9 IDE freshly reinstalled
COM14 port in Arduino IDE checked
Under Device Manager COM14 shows as: "USB Serial Port (COM14)". Not as "Arduino...(COM14)" as some pages have shown
I am not sure if I have a real or copy of the Arduino. As far as I can figure out I have a real one, on the back I have the FT232RL chip
I have bought 2 Arduino Nanos and both show same error
Both Nanos came pre-soldered, (no noob soldering by me)
I have tried uploading sketches on my Win7 platform AND over a Raspberry Pi, both same error

Now perhaps most importantly I previously ordered an Arduino from the same retailer and that one worked. The two I have now dont work.
The problem:

When I try upload I get the same message every time: avrdude: stk500_recv(): programmer is not responding
a. it does this 10 times and then fails
b. Rx and Tx LED's are ON and do NOT blink at all at any point in time
c. Green power LED is always ON, no blinking
d. Pin13 LED blinks consistently
e. I have tried the extreemly annoying reset "trick" before uploading, after uploading, at the same time, during uploading, and nothing works

I am seriously at a loss here. I have had an Arduino Nano work on my pc.
Any help would be greatly appreciated please.

The Arduino.cc developers changed the bootloader on official Arduino Nanos to communicate at a different speed. Try setting Tools → Processor → ATmega328P (Old Bootloader)

This worked for me, thank you!

Sorry for posting this as an answer, I don't have enough rep to write comments yet.
1) Have you tried different USB cables? A dodgy USB cable could power the Nano just fine, giving the impression that it's properly connected, without not actually supporting the data rate required for programming. The fact that something shows up on a USB port on your computer makes this explanation less plausible, though.
2) I notice that there are different versions of the Nano, some with ATmega168 and some with ATmega328. If you have the ATmega328, maybe try selecting "Arduino Uno" in the IDE? If you have the ATmega168, maybe try "Arduino Mini"?

The baudrate for those is 57600. Try checking for an error in your boards.txt .

Do you have experience with this? I've never seen any board using 57600 as a baud rate (not saying it doesn't exist), to me it sounds more like a driver issue. A link to a datasheet or other web reference would go a long way to support your (short) answer

Yes, all my nano clones use it for UPLOAD_RATE . Can't very well give you a datasheet reference, the chinese vendors are not that verbose.

And my 3V minis from RobotDyn will only accept 19200 baud...

... and for the sake of completeness: my uno clones use 115200, and my pro mini 5V clones use 57600 baud.

try a different COM port. I had a corrupted COM3 and it gave the exact same error message that you got

If the Arduino is connected to COM3 then he can't just change to a different COM port.


text:
Relay to Mains lightswitch
So I purchased a 4 channel Relay which handles AC250V 10A ; DC30V 10A.
But am I able to connect this to replace a light switch so I can automate it?  My bedroom runs on 15 amps.

http://amazon.com/gp/product/B00VHVIBAM?psc=1&redirect=true&ref_=oh_aui_detailpage_o00_s00

You can. But if it's a wall switch, it may be required to have an electrician do this, in your country. The 15Amps is the maximum current. Unless you are using a 2000 Watt light bulb, you won't reach the 10A limit of the relay. Remember to be careful, while working with mains voltage.

I have been working with mains lately, but I just don't know if the relay will blow out with the 15 amps.  But thank you!

It will only, if you have a device attached that uses more than 10 amps.

I'm voting to close this question as off-topic because it is about mains electrical wiring not Arduino.

All mains electrical work should be performed by a fully qualified electrician.
Yes, this relay board will easily switch a light bulb.
A note on current: A single 100 Watt incandescent globe will only draw 0.83 Amps at 120V AC (0.416 Amps at 240V AC). The equation I used: I=P/V. You would start coming close to the maximum rating after 10 globes (although I advise staying well below the maximum).
You mention that your bedroom runs on 15 Amps, which I assume means that the mains runs through a 15 Amp circuit breaker (or fuse). This circuit breaker will trip if the total current to all devices after it exceeds 15 Amps.
A similar question was asked by Matthieu Napoli over on the Electrical Engineering Stack Exchange site. There are a number of high quality answers there that would be helpful for you. Worthiest to mention is Cybergibbons answer where he recommends using the PowerSwitch Tail as a very safe way of switching mains voltage. You don't need an electrician when using the PowerSwitch Tail providing the light you are controlling has the matching plugs.


text:
Interfacing key-pad with arduino with 7 segment display
I have the following components:

Arduino Mega
7-segment display
12-digit key-pad

For my project, I would like to display on the 7-segment display the number that the user presses on the keypad.

Try this: please note that you have to fill in the last function in order to get an int value from your keypad. The 7-segments part of the code should be fine.
const int segment[7] = {2,3,4,5,6,7,8}; //pins for each segment

const int nums[10][7] = //declaring array
{
  {1,1,1,1,1,1,0}, //0
  {0,1,1,0,0,0,0}, //1
  {1,1,0,1,0,0,1}, //2
  {1,1,1,1,0,0,1}, //3
  {0,1,1,0,0,1,1}, //4
  {1,0,1,1,0,1,1}, //5
  {1,0,1,1,1,1,1}, //6
  {1,1,1,0,0,0,0}, //7
  {1,1,1,1,1,1,1}, //8
  {1,1,1,0,0,1,1}  //9
};

void setup() {
  for(int i=2; i<=8; i++) //shorcut for declaring a buch of pin modes
  {
    pinMode(i, OUTPUT);
  }
}

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

void loop() {
  number(keypadInput);
}

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

void number(int num) //num is the number to display
{
  for(int i=0; i<7; i++)
  {
    digitalWrite(segment[i], nums[num][i]);
  }
}

int (keypadInput)
{
  //code for getting the input of your keypad
}

Thank you for your answer. I will definitely add this code once I get my keypad.  Thanks a lot.


text:
Digispark / DigiKeyboard change keyboard layout
I'm trying to use the Digispark as a Rubber Ducky but the Digispark is only usable with the US laylout. German keyboard layout is QWERTZ. Some keys can be changed, like y and z, but if there are [ or ] this isn't possible. Trying to define a [-key in DigiKeyboard.h displays a ü.
Does someone know a solution?

You can edit the file scancode-ascii-table.h in your DigiKeyboard library.
It basically states which ASCII code corresponds to which keyboard scancode.
So if you try to print the ':' character but get a '>' instead, you know that in the above mentioned file at the ASCII position for ':' is the scancode for a '>'.
Using this, you can swap the scancodes around and basically create your own 'mapping'. For example, if you swap the values at ASCII 89, 90 and 121, 122 you for example solve the Y/Z switch.
However, I have not figured out how to correctly print a backslash. You might have to map that do a different ASCII character you don't need.
To add to this answer, there exists a workaround using mame82's duck2spark:
https://github.com/mame82/duck2spark

Solution is here:
Python script to convert RubberDucky payloads to DigiSpark sketch with respect to choosen keyboard layout:
duck2spark
Btw: The keys '<' '|' and '>' are on NON-US-KEY-100 on German keyboard layout. The key has value 0x64 for USB HID and the right modifiers have to be set (f.e. ALT_GR for '|' ). You could send them using
DigiKeyboard.sendKeyStroke(key,modifier);

For details see USB HID usage tables

here is a library version of Digistump with german keyboard support https://github.com/adnanonline/DigistumpArduinoDe
I adapted the keyboard library: digistump-avr/libraries/DigisparkKeyboard/DigiKeyboard.h to the german layout


text:
FTDI and atmega328p-au
I want to connect an Arduino Pro Mini with ATmega328P so as to drive a SI4463. But I don't know BLK, CTS, DTR should be connected to what pins of ATmega328P.
How do I connect this?

If you're trying to build an ATmega circuit and asking about it on the Arduino site, shouldn't you review the published schematic of a comparable Arduino, ie, one using the same 5-pin FTDI header???  Additionally you should probably consider prototyping this with a modular Arduino before making a board - the Si4463 is non-trivial in complexity even if on a module, and in addition to helping prove your plans, a prototype around an Arduino will let you get started on the software tasks while your PCB is being fabricated.

BLK is ground.
CTS is generally not used. I leave it unconnected on my boards.
DTR goes to the auto-reset circuit.
Update:

Can I let DTR directly connect with RESET ?

Auto-reset circuits use a .1uf capacitor between the DTR (or RTS, depends on which one your cable supplies) and the reset pin. (The exact value probably isn't too important). Without it, the reset circuit is likely pick up noise and randomly reset the Arduino.

Can I let DTR directly connect with RESET ?

You can’t connect it directly, because it is low when a connection is made.  So it will keep the Arduino in reset-mode all the time. So the bootloader will never run, and you can’t upload any new code or run existing code.

Also a good idea to have a diode in parallel with the resistor - cathode to 5V.  Keeps any high voltage spikes on the Reset line from kicking off the High Voltage programming sequence and the chip then acting hung.


text:
How to merge HCSR04 code with DF Player mini mp3
As the title says, I have a problem to merging the HCSR04 code with DF Player mini mp3 codebases so that they are working together in the one sketch.
The idea is when the ultrasonic sensor reads a certain range, it will trigger a specific mp3 files via the DF player.
I'm using 5 Ultrasonic sensors, and I wanted each sensors to trigger different mp3 files.
Ultrasonic code:
int trigPin1=2;
int echoPin1=3;

int trigPin2=4;
int echoPin2=5;

int trigPin3=6;
int echoPin3=7;

int trigPin4=8;
int echoPin4=9;

int trigPin5=10;
int echoPin5=11;

void setup() {
  Serial.begin (9600);
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);
  pinMode(trigPin3, OUTPUT);
  pinMode(echoPin3, INPUT);
  pinMode(trigPin4, OUTPUT);
  pinMode(echoPin4, INPUT);
  pinMode(trigPin5, OUTPUT);
  pinMode(echoPin5, INPUT);

}

void loop() {
  long duration1, distance1;
  digitalWrite(trigPin1, LOW);  // Added this line
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin1, HIGH);
  delayMicroseconds(15); // Added this line
  digitalWrite(trigPin1, LOW);
  duration1 = pulseIn(echoPin1, HIGH);
  distance1 = duration1/58;

long duration2, distance2;
  digitalWrite(trigPin2, LOW);  // Added this line
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin2, HIGH);
  delayMicroseconds(15); // Added this line
  digitalWrite(trigPin2, LOW);
  duration2 = pulseIn(echoPin2, HIGH);
  distance2= duration2/58;

long duration3, distance3;
  digitalWrite(trigPin3, LOW);  // Added this line
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin3, HIGH);
  delayMicroseconds(15); // Added this line
  digitalWrite(trigPin3, LOW);
  duration3 = pulseIn(echoPin3, HIGH);
  distance3= duration3/58;

  long duration4, distance4;
  digitalWrite(trigPin4, LOW);  // Added this line
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin4, HIGH);
  delayMicroseconds(15); // Added this line
  digitalWrite(trigPin4, LOW);
  duration4 = pulseIn(echoPin4, HIGH);
  distance4= duration4/58;

  long duration5, distance5;
  digitalWrite(trigPin5, LOW);  // Added this line
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin5, HIGH);
  delayMicroseconds(15); // Added this line
  digitalWrite(trigPin5, LOW);
  duration5 = pulseIn(echoPin5, HIGH);
  distance5= duration5/58;

  Serial.print (distance1);
  Serial.print (",");
  Serial.print(distance2);
  Serial.print(",");
  Serial.print(distance3);
  Serial.print(",");
  Serial.print(distance4);
  Serial.print(",");
  Serial.print(distance5);
  Serial.println(",");
  delay(100);

}

DF Player code:
#include "Arduino.h"
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"

SoftwareSerial mySoftwareSerial(12, 13); // RX, TX
DFRobotDFPlayerMini myDFPlayer;
void printDetail(uint8_t type, int value);

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

  Serial.println();
  Serial.println(F("DFRobot DFPlayer Mini Demo"));
  Serial.println(F("Initializing DFPlayer ... (May take 3~5 seconds)"));

  if (!myDFPlayer.begin(mySoftwareSerial)) {  //Use softwareSerial to communicate with mp3.
    Serial.println(F("Unable to begin:"));
    Serial.println(F("1.Please recheck the connection!"));
    Serial.println(F("2.Please insert the SD card!"));
    while(true);
  }
  Serial.println(F("DFPlayer Mini online."));

  myDFPlayer.volume(10);  //Set volume value. From 0 to 30
}

void loop()
{
  static unsigned long timer = millis();

  if (millis() - timer > 2000) {
    timer = millis();
    myDFPlayer.next();  //Play next mp3 every 3 second.
  }

  if (myDFPlayer.available()) {
    printDetail(myDFPlayer.readType(), myDFPlayer.read()); //Print the detail message from DFPlayer to handle different errors and states.
  }
}

void printDetail(uint8_t type, int value){
  switch (type) {
    case TimeOut:
      Serial.println(F("Time Out!"));
      break;
    case WrongStack:
      Serial.println(F("Stack Wrong!"));
      break;
    case DFPlayerCardInserted:
      Serial.println(F("Card Inserted!"));
      break;
    case DFPlayerCardRemoved:
      Serial.println(F("Card Removed!"));
      break;
    case DFPlayerCardOnline:
      Serial.println(F("Card Online!"));
      break;
    case DFPlayerPlayFinished:
      Serial.print(F("Number:"));
      Serial.print(value);
      Serial.println(F(" Play Finished!"));
      break;
    case DFPlayerError:
      Serial.print(F("DFPlayerError:"));
      switch (value) {
        case Busy:
          Serial.println(F("Card not found"));
          break;
        case Sleeping:
          Serial.println(F("Sleeping"));
          break;
        case SerialWrongStack:
          Serial.println(F("Get Wrong Stack"));
          break;
        case CheckSumNotMatch:
          Serial.println(F("Check Sum Not Match"));
          break;
        case FileIndexOut:
          Serial.println(F("File Index Out of Bound"));
          break;
        case FileMismatch:
          Serial.println(F("Cannot Find File"));
          break;
        case Advertise:
          Serial.println(F("In Advertise"));
          break;
        default:
          break;
      }
      break;
    default:
      break;
  }

}

Please clarify your question.

How to merge these 2 codes, I tried many ways but can find the right one, i'm literally new to writing codes like this

I've refactored it a bit, to remove the need to repeat the same code, 5 times, for 5 sensors.
#include "Arduino.h"
#include "SoftwareSerial.h"

#include "DFRobotDFPlayerMini.h"

const byte SENSOR_COUNT = 5;
byte triggerPins[SENSOR_COUNT] = {2,4,6,8,10};
byte echoPins[SENSOR_COUNT]    = {3,5,7,9,11};

SoftwareSerial mySoftwareSerial(12, 13); // RX, TX

DFRobotDFPlayerMini myDFPlayer;

void printDetail(uint8_t type, int value);

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

  for( byte i=0; i<SENSOR_COUNT; i++ )
  {
    pinMode(triggerPins[i], OUTPUT);
    pinMode(echoPins[i], INPUT);
  }

  Serial.println();
  Serial.println(F("DFRobot DFPlayer Mini Demo"));
  Serial.println(F("Initializing DFPlayer ... (May take 3~5 seconds)"));

  if (!myDFPlayer.begin(mySoftwareSerial)) {  //Use softwareSerial to communicate with mp3.
    Serial.println(F("Unable to begin:"));
    Serial.println(F("1.Please recheck the connection!"));
    Serial.println(F("2.Please insert the SD card!"));
    while(true);
  }
  Serial.println(F("DFPlayer Mini online."));

  myDFPlayer.volume(10);  //Set volume value. From 0 to 30

}

int currentSound = -1;
void loop()
{

  for( byte i=0; i<SENSOR_COUNT; i++ ) // loop through all distance sensors
  {
    if( detectPresence(i) ) // check if there is an object near it
    {
      if(currentSound!=i) // check that it's a different sensor than the one that was last triggered
      {
        Serial.print("play song number ");
        Serial.println(i);
        myDFPlayer.play(i+1); // play song nr `i+1`
      }
      currentSound = i;
    }
  }

  if (myDFPlayer.available()) {
    printDetail(myDFPlayer.readType(), myDFPlayer.read()); //Print the detail message from DFPlayer to handle different errors and states.
  }

}

// detectPresence will return TRUE if there is an object close to it.
bool detectPresence(byte sensorNr)
{
  if( sensorNr>=SENSOR_COUNT )
    return false;
  long duration, distance;
  //digitalWrite(triggerPins[sensorNr], LOW);  // Added this line
  //delayMicroseconds(10); // Added this line
  digitalWrite(triggerPins[sensorNr], HIGH);
  delayMicroseconds(15); // Added this line
  digitalWrite(triggerPins[sensorNr], LOW);
  duration = pulseIn(echoPins[sensorNr], HIGH);
  distance = duration/58;

  return distance<30;// choose your own value here, from which distance it should trigger a sound
}

void printDetail(uint8_t type, int value){

  switch (type) {
    case TimeOut:
      Serial.println(F("Time Out!"));
      break;
    case WrongStack:
      Serial.println(F("Stack Wrong!"));
      break;
    case DFPlayerCardInserted:
      Serial.println(F("Card Inserted!"));
      break;
    case DFPlayerCardRemoved:
      Serial.println(F("Card Removed!"));
      break;
    case DFPlayerCardOnline:
      Serial.println(F("Card Online!"));
      break;
    case DFPlayerPlayFinished:
      Serial.print(F("Number:"));
      Serial.print(value);
      Serial.println(F(" Play Finished!"));
      break;
    case DFPlayerError:
      Serial.print(F("DFPlayerError:"));
      switch (value) {
        case Busy:
          Serial.println(F("Card not found"));
          break;
        case Sleeping:
          Serial.println(F("Sleeping"));
          break;
        case SerialWrongStack:
          Serial.println(F("Get Wrong Stack"));
          break;
        case CheckSumNotMatch:
          Serial.println(F("Check Sum Not Match"));
          break;
        case FileIndexOut:
          Serial.println(F("File Index Out of Bound"));
          break;
        case FileMismatch:
          Serial.println(F("Cannot Find File"));
          break;
        case Advertise:
          Serial.println(F("In Advertise"));
          break;
        default:
          break;
      }
      break;
    default:
      break;
  }

}

Thank you very much Gerben! this works absolutely perfect, buy yet there is one last problem, sensor #1 now trigger mp3 player to play "song #0", how do i switch it so sensor #1 plays song #1, sensor #2 plays song #2 and so on? thank you for all your help man! appreciate it much!

It should already do that! Doesn't it? There is only a problem if multiple sensors are triggering at the same time.

From what i'm seen and heard, when sensor#1 triggered it plays song#0 and its not playing anything since the DFPlayer files start with 1, not 0, or something, correct me if i'm wrong but it does plays song#0, and nothing come out, and the first file on my mp3 list played when sensor#2 triggered. so it become Sensor#1 Plays Song#0, Sensor#2 plays Song#1... Sensor#5 plays Song#4

I've changed myDFPlayer.play(i); to myDFPlayer.play(i+1); in the code above. That should fix that.


text:
How to run multiple functions one after another?
I want to fade a red LED up and down, then a green LED up and down, and repeat the whole cycle indefinitely.
I've been trying to run multiple functions one after another. However my current code seems to have them both fading in parallel.
I tried using a switch case, do while and the while loop but the code runs the two functions at once. So what is wrong with the code below?
This is my code:
void setup() {
    Serial.begin(9600);
    DDRD |= (1<<DDD6)|(1<<DDD5);
    TCCR0A = 0xF1;
}

uint8_t fade_seq;

void loop() {
    loop1:
    fade_seq++;
    while (fade_seq==1)
    {
        fade_red(1);
    }
    Serial.println(fade_seq);
    while (fade_seq==2)
    {
        fade_green(1);
    }
    if (fade_seq==3)
    {
        fade_seq=0;
        goto loop1;
    }
}

void fade_red(uint8_t cnt)
{
    uint8_t i,k;
    for (k=0;k<cnt;k++)
    {
        OCR0A+=1;
        _delay_ms(10);
        if (OCR0A == 255)
        {
            for (i=0;i<255;i++)
            {
                OCR0A--;
                _delay_ms(10);
            }
        }
    }
}

void fade_green(uint8_t cnt)
{
    uint8_t i,k,c;
    for (c=0;c<cnt;c++)
    {
        for (k=0;k<255;k++)
        {
            OCR0B+=1;
            _delay_ms(10);
            if (OCR0B == 255)
            {
                for (i=0;i<255;i++)
                {
                    OCR0B--;
                    _delay_ms(10);
                }
            }
        }
    }
}

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

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

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

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

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

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

I did not quite understand what you are actually trying to accomplish.
Neither you question nor your code is very clear in this respect. And
your code is probably buggy anyway, since it does not do what you
expect.
Then, I am just guessing: you may just want to fade a red LED up and
down, then a green LED up and down, and repeat the whole cycle
indefinitely. I am guessing right?
First of all, I would recommend you stick with the functions provided by
the Arduino core library, as they will make your life easier. The kind
of low level AVR programming you are attempting here is for advanced
users. You should learn the basics first before moving to that realm.
Here is how I would write that using the plain analogRead() function:
const uint8_t RED   = 6;  // pin connected to the red LED
const uint8_t GREEN = 5;  // pin connected to the green LED

void setup()
{
    Serial.begin(9600);
    pinMode(RED, OUTPUT);
    pinMode(GREEN, OUTPUT);
}

// Fade an analog pin up and down.
void fade(uint8_t pin)
{
    for (int i = 1; i <= 255; i++) {
        analogWrite(pin, i);
        delay(10);
    }
    for (int i = 254; i >= 0; i--) {
        analogWrite(pin, i);
        delay(10);
    }
}

void loop()
{
    Serial.println(F("Fading RED."));
    fade(RED);
    Serial.println(F("Fading GREEN."));
    fade(GREEN);
}

Each LED fading up and down takes roughly 5 seconds:
2 ramps × 255 steps/ramp × 10 ms/step.

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

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

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

It simply is not possible for the processor to run both functions at once. What probably is happening is that the sequence of functions executes too fast to distinguish it as two sequential processes. You'll need to do something like call them with a delay in between. It could be as simple as:
void loop() {
   fade_red();
   delay(500);

   fade_green();
   delay(500);
}

The while loops surrounding your calls do nothing at all. The effect of each one is to call its respective function once. Your code is pretty much equivalent to a switch/case statement using fade_seq as the selector, but without any control over the timing of your calls, the functions will happen in rapid sequence.

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

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

Why my loops are very complicated?

OK, here is your loop:
uint8_t fade_seq;   // <--- initially zero

void loop() {
loop1:
fade_seq++;
while (fade_seq==1)
{
  fade_red(1);
}
Serial.println(fade_seq);
while (fade_seq==2)
{
  fade_green(1);
}
if (fade_seq==3)
{
  fade_seq=0;
  goto loop1;
}
}

So you add 1 to fade_seq and then:
while (fade_seq==1)
{
  fade_red(1);
}

So fade_seq is always 1 so that loops indefinitely. Therefore you can forget about everything else after it.
So you may as well write:
void loop() {
   while (true)
    {
    fade_red(1);
    }
 }

And since loop, well, loops, that simplifies to:
void loop() {
    fade_red(1);
   }

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

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

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

try this-and add to it calling a function in between-as discussed in comments that gives a visible delay-note I increased the delays as its probably going too fast
uint8_t fade_seq=1;
 void setup() {
DDRD |= (1<<DDD6)|(1<<DDD5);
TCCR0A = 0xF1;
}

void loop() {
fade_seq++;
if (fade_seq==1)
{
  fade_red(1);

}

if (fade_seq==2)
{
  fade_green(1);

}
if (fade_seq==3)
{
fade_seq=0;
}
}

void fade_red(uint8_t cnt)
{
  uint8_t i,k;
  for (k=0;k<cnt;k++)
  {
    OCR0A+=1;
    _delay_ms(100);
    if (OCR0A == 255)
    {
      for (i=0;i<255;i++)
      {
        OCR0A--;
        _delay_ms(100);
      }
    }
  }
}

void fade_green(uint8_t cnt)
{
  uint8_t i,k;
  for (k=0;k<cnt;k++)
  {
    OCR0B+=1;
    _delay_ms(1-0);
    if (OCR0B == 255)
    {
      for (i=0;i<255;i++)
      {
        OCR0B--;
        _delay_ms(100);
      }
    }
  }
}

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

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

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

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

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

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

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

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

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

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

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

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

Let us continue this discussion in chat.

OK I did it :)
void setup() {
DDRD |= (1<<DDD6)|(1<<DDD5);
TCCR0A = 0xF1;
}

void loop() {
  fade_red(255);
  fade_green(255);
}

void fade_red(uint8_t cnt)
{
  uint8_t i,k;
  for (k=0;k<cnt;k++)
  {
    OCR0A++;
    _delay_ms(10);
    if (OCR0A == 255)
    {
      for (i=0;i<255;i++)
      {
        OCR0A--;
        _delay_ms(10);
      }
    }
  }
}
void fade_green(uint8_t cnt)
{
  uint8_t i,k;
  for (k=0;k<cnt;k++)
  {
    OCR0B++;
    _delay_ms(10);
    if (OCR0B == 255)
    {
      for (i=0;i<255;i++)
      {
        OCR0B--;
        _delay_ms(10);
      }
    }
  }
}

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

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

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

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

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

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

Aye, that I did. :)


text:
Why can't I use Jeelib Sleepy on the Teensy 2 along with Serial
I have been using the Jeelib Sleepy functionality for several years now to achieve low power states on the Arduino ATmega328/1280/2560 boards, specifically the LoseSomeTime functionality.
I want to get my Teensy 2 to go into a similar low power state, so I tried a very simple sketch that simply put the device to sleep, flashed an LED, and posted some Serial messages. I did need to comment out a few lines in Jeelib:
// adjust the milli ticks, since we will have missed several
#if defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny85__) || defined (__AVR_ATtiny44__) || defined (__AVR_ATtiny45__)
    extern volatile unsigned long millis_timer_millis;
    millis_timer_millis += msecs - msleft;
#else
    extern volatile unsigned long timer0_millis;
    timer0_millis += msecs - msleft;
#endif

This had to be done as the delay() and millis() functions on the Teensy use different variable names for the adjustment, and it was the quickest way of solving the problem. LoseSomeTime works on the ATmega328 hardware with this change.
I found that although the LoseSomeTime function did sleep for a period, the Serial functionality stopped working entirely - no messages were being printed at all. I have encountered this before on ATmega328 hardware because the microcontroller has gone to sleep before the serial buffer was flushed. I added a number of delay()s after the Serial.writes and also tried using Serial.flush() to make sure the buffer was empty.
LoseSomeTime requires setting an interrupt on the watchdog timer, but I can't see how this would impact Serial operation.

You explicitly mention Teensy 2 for this issue, does it mean you have tried on other boards and did not encounter that problem? It looks so in your question, but it's not 100% clear on that point. It could be useful to mention a list of boards on which the same sketch works or doesn't work, in case you could test on different plqtforms.

Not a problem on any ATmega328, ATmega1280, ATmega2560 boards. I haven't tried on a Teensy 2++. I know it won't work with any of the ARM boards.

Does it have anything to do that serial is based on interrupts now? Could that affect it? I've never used the library though or the Teensy 2, so I don't know much about this situation, but I might look into it if I have time.

I think both an Uno and Teensy use interrupts for serial, don't they? At least since v1 of the IDE.

This is a problem with the Teensy boards - or more correctly that the Jeelib Sleepy library does not support the Teensy boards.
You will need to modify the library to make it work for Teensy boards. Or you could use another low power/sleep library.


text:
Reading three signals sent serially on Simulink from Arduino
I am sending three signals from one Arduino mega to another using xbees. On the receiving end I am using these signals in a Simulink code to control servo motors. Currently it is set up to read from analog pins without the wireless set up. With the wireless technology the signals are all being sent and received through one serial port. I believe I would need to change the inputs in Simulink to a serial receive block instead of an analog pin block. The problem is the documentation for the serial receive block says you can not assign more than one serial receive block to the same serial port. If anyone has a solution to this it would be greatly appreciated!
receiving code
int received1;
int received2;
int received3;
void setup() {
  Serial.begin(9600);
}
void loop() {
  if(Serial.available() )
  {
    received1, received2, received3 = Serial.read();
  }
}

transmitting code:
void setup() {
  Serial.begin(9600);
}

void loop() {
  int sensorValue1 = analogRead(A0);
  int sensorValue2 = analogRead(A1);
  int sensorValue3 = analogRead(A2);
  Serial.write(sensorValue1, sensorValue2, sensorValue3);
  delay(1);
}

How are the three signals encoded in the bitstream?

Here is my receiving end arduino code. Not sure if its correct yet.  I will add it to the question.

What does your sending code look like?

I will add that to the question as well

What is the result shown on the serial monitor?
Let the three values received on the receiver code be shown on the serial monitor. Tell us exactly what do you have? Is it a trash? or nothing is received?

Repost from SO: http://stackoverflow.com/questions/22599430/reading-three-signals-sent-serially-on-simulink-from-arduino

You need to put your data into a packet and then send the packet to Simulink.
You have tried this by this line in your transmitting code:
Serial.write(sensorValue1, sensorValue2, sensorValue3);

However, as you can see from the Serial Write documentation it does not work like that. The function cannot accept 3 arguments.
Try this instead:
Serial.write(sensorValue1);
Serial.write(sensorValue2);
Serial.write(sensorValue3);