title: TPS/MAP calculation problem - SOLVED

text:
# Question
Title: TPS/MAP calculation problem - SOLVED
In my recent project, I have to create TPS/MAP table, which is provide value of LOAD.

Here, it is my table. You can see two value of LOAD which is separate by /. (TPS LOAD / MAP LOAD)

But now here as you can see, TPS provide different value of LOAD and MAP provide different value of LOAD. So, every cell has a two value of LOAD. So, I decide just add this both LOAD and divide it by 2.

I made program for this but it access only just LAST COLUMN and LAST ROW and it provide wrong value of LOAD. I don't understand why this happen.

Here, my code.

```
float TPS[] = {0, 0.4, 0.8, 1.2, 1.6, 2, 2.4, 2.8, 3.2, 3.6, 4, 4.4, 4.8, 5};
float MAP[] = {0.85, 0.95, 1.05, 1.15, 1.25, 1.35, 1.45, 1.55, 1.65, 1.75, 1.85, 1.9};

float TPS_MIN = 0.00;
float TPS_MAX = 5.00;

float MAP_MIN = 0.85;
float MAP_MAX = 1.90;

float LOAD_MIN_TPS[] = {2, 3.23, 4.49, 5.73, 6.97, 8.22, 9.44, 10.63, 11.87, 13.11, 14.33, 15.00};
float LOAD_MAX_TPS[] = {10.00, 17.08, 24.11, 31.67, 38.30, 45.73, 52.63, 60.19, 67.22, 74.52, 81.68, 85.00};

float LOAD_MIN_MAP[] = {2, 2.64, 3.28, 3.92, 4.56, 5.21, 5.85, 6.47, 7.11, 7.76, 8.40, 9.05, 9.69, 10.00};
float LOAD_MAX_MAP[] = {15.00, 20.62, 26.17, 31.79, 37.35, 42.97, 48.66, 54.14, 59.76, 65.38, 70.93, 76.63, 82.18, 85.00};

float m1[12] = {};
float m2[14] = {};

float y1[14] = {};
float y2[12] = {};

float y[168] = {};

int i, j, n;

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

void loop()
{
  for(j = 0; j < 12; j++)
  {
    m1[j] = (LOAD_MAX_TPS[j] - LOAD_MIN_TPS[j]) / (TPS_MAX - TPS_MIN);

    Serial.print("m1 : ");
    Serial.println(m1[j]);

    for(i = 0; i < 14; i++)
    {
      y1[i] = m1[j] * (TPS[i] - TPS_MIN) + LOAD_MIN_TPS[j];

      Serial.print("TPS : ");
      Serial.print(TPS[i]);
      Serial.print("\t");
      Serial.print("LOAD : ");
      Serial.println(y1[i]);
   }
  }

  for(i = 0; i < 14; i++)
  {
    m2[i] = (LOAD_MAX_MAP[i] - LOAD_MIN_MAP[i]) / (MAP_MAX - MAP_MIN);

    Serial.print("m2 : ");
    Serial.println(m2[i]);

    for(j = 0; j < 12; j++)
    {
      y2[j] = m2[i] * (MAP[j] - MAP_MIN) + LOAD_MIN_MAP[i];

      Serial.print("MAP : ");
      Serial.print(MAP[j]);
      Serial.print("\t");
      Serial.print("LOAD : ");
      Serial.println(y2[j]);
    }
   }

  for(i = 0; i < 14; i++)
  {
    for(j = 0; j < 12; j++)
    {
      y[n] = (y1[i] + y2[j]) / 2;
      Serial.print("LOAD TPS : ");
      Serial.print(y1[i]);
      Serial.print("\t");
      Serial.print("LOAD MAP : ");
      Serial.print(y2[j]);
      Serial.print("\t");
      Serial.print("TPS : ");
      Serial.print(TPS[i]);
      Serial.print("\t");
      Serial.print("MAP : ");
      Serial.print(MAP[j]);
      Serial.print("\t");
      Serial.print("Final LOAD : ");
      Serial.println(y[n]);
    }
  }
  delay(1000000);
}

```

My serial monitor output :

```
LOAD TPS : 15.00    LOAD MAP : 10.00    TPS : 0.00  MAP : 0.85  Final LOAD : 12.50
LOAD TPS : 15.00    LOAD MAP : 17.14    TPS : 0.00  MAP : 0.95  Final LOAD : 16.07
LOAD TPS : 15.00    LOAD MAP : 24.29    TPS : 0.00  MAP : 1.05  Final LOAD : 19.64
LOAD TPS : 15.00    LOAD MAP : 31.43    TPS : 0.00  MAP : 1.15  Final LOAD : 23.21
LOAD TPS : 15.00    LOAD MAP : 38.57    TPS : 0.00  MAP : 1.25  Final LOAD : 26.79
LOAD TPS : 15.00    LOAD MAP : 45.71    TPS : 0.00  MAP : 1.35  Final LOAD : 30.36
LOAD TPS : 15.00    LOAD MAP : 52.86    TPS : 0.00  MAP : 1.45  Final LOAD : 33.93
LOAD TPS : 15.00    LOAD MAP : 60.00    TPS : 0.00  MAP : 1.55  Final LOAD : 37.50
LOAD TPS : 15.00    LOAD MAP : 67.14    TPS : 0.00  MAP : 1.65  Final LOAD : 41.07
LOAD TPS : 15.00    LOAD MAP : 74.29    TPS : 0.00  MAP : 1.75  Final LOAD : 44.64
LOAD TPS : 15.00    LOAD MAP : 81.43    TPS : 0.00  MAP : 1.85  Final LOAD : 48.21
LOAD TPS : 15.00    LOAD MAP : 85.00    TPS : 0.00  MAP : 1.90  Final LOAD : 50.00
LOAD TPS : 20.60    LOAD MAP : 10.00    TPS : 0.40  MAP : 0.85  Final LOAD : 15.30
LOAD TPS : 20.60    LOAD MAP : 17.14    TPS : 0.40  MAP : 0.95  Final LOAD : 18.87
LOAD TPS : 20.60    LOAD MAP : 24.29    TPS : 0.40  MAP : 1.05  Final LOAD : 22.44
LOAD TPS : 20.60    LOAD MAP : 31.43    TPS : 0.40  MAP : 1.15  Final LOAD : 26.01
LOAD TPS : 20.60    LOAD MAP : 38.57    TPS : 0.40  MAP : 1.25  Final LOAD : 29.59
LOAD TPS : 20.60    LOAD MAP : 45.71    TPS : 0.40  MAP : 1.35  Final LOAD : 33.16
LOAD TPS : 20.60    LOAD MAP : 52.86    TPS : 0.40  MAP : 1.45  Final LOAD : 36.73
LOAD TPS : 20.60    LOAD MAP : 60.00    TPS : 0.40  MAP : 1.55  Final LOAD : 40.30
LOAD TPS : 20.60    LOAD MAP : 67.14    TPS : 0.40  MAP : 1.65  Final LOAD : 43.87
LOAD TPS : 20.60    LOAD MAP : 74.29    TPS : 0.40  MAP : 1.75  Final LOAD : 47.44
LOAD TPS : 20.60    LOAD MAP : 81.43    TPS : 0.40  MAP : 1.85  Final LOAD : 51.01
LOAD TPS : 20.60    LOAD MAP : 85.00    TPS : 0.40  MAP : 1.90  Final LOAD : 52.80
LOAD TPS : 26.20    LOAD MAP : 10.00    TPS : 0.80  MAP : 0.85  Final LOAD : 18.10
LOAD TPS : 26.20    LOAD MAP : 17.14    TPS : 0.80  MAP : 0.95  Final LOAD : 21.67
LOAD TPS : 26.20    LOAD MAP : 24.29    TPS : 0.80  MAP : 1.05  Final LOAD : 25.24
LOAD TPS : 26.20    LOAD MAP : 31.43    TPS : 0.80  MAP : 1.15  Final LOAD : 28.81
LOAD TPS : 26.20    LOAD MAP : 38.57    TPS : 0.80  MAP : 1.25  Final LOAD : 32.39
LOAD TPS : 26.20    LOAD MAP : 45.71    TPS : 0.80  MAP : 1.35  Final LOAD : 35.96
LOAD TPS : 26.20    LOAD MAP : 52.86    TPS : 0.80  MAP : 1.45  Final LOAD : 39.53
LOAD TPS : 26.20    LOAD MAP : 60.00    TPS : 0.80  MAP : 1.55  Final LOAD : 43.10
LOAD TPS : 26.20    LOAD MAP : 67.14    TPS : 0.80  MAP : 1.65  Final LOAD : 46.67
LOAD TPS : 26.20    LOAD MAP : 74.29    TPS : 0.80  MAP : 1.75  Final LOAD : 50.24
LOAD TPS : 26.20    LOAD MAP : 81.43    TPS : 0.80  MAP : 1.85  Final LOAD : 53.81
LOAD TPS : 26.20    LOAD MAP : 85.00    TPS : 0.80  MAP : 1.90  Final LOAD : 55.60
LOAD TPS : 31.80    LOAD MAP : 10.00    TPS : 1.20  MAP : 0.85  Final LOAD : 20.90
LOAD TPS : 31.80    LOAD MAP : 17.14    TPS : 1.20  MAP : 0.95  Final LOAD : 24.47
LOAD TPS : 31.80    LOAD MAP : 24.29    TPS : 1.20  MAP : 1.05  Final LOAD : 28.04
LOAD TPS : 31.80    LOAD MAP : 31.43    TPS : 1.20  MAP : 1.15  Final LOAD : 31.61
LOAD TPS : 31.80    LOAD MAP : 38.57    TPS : 1.20  MAP : 1.25  Final LOAD : 35.19
LOAD TPS : 31.80    LOAD MAP : 45.71    TPS : 1.20  MAP : 1.35  Final LOAD : 38.76
LOAD TPS : 31.80    LOAD MAP : 52.86    TPS : 1.20  MAP : 1.45  Final LOAD : 42.33
LOAD TPS : 31.80    LOAD MAP : 60.00    TPS : 1.20  MAP : 1.55  Final LOAD : 45.90
LOAD TPS : 31.80    LOAD MAP : 67.14    TPS : 1.20  MAP : 1.65  Final LOAD : 49.47
LOAD TPS : 31.80    LOAD MAP : 74.29    TPS : 1.20  MAP : 1.75  Final LOAD : 53.04
LOAD TPS : 31.80    LOAD MAP : 81.43    TPS : 1.20  MAP : 1.85  Final LOAD : 56.61
LOAD TPS : 31.80    LOAD MAP : 85.00    TPS : 1.20  MAP : 1.90  Final LOAD : 58.40
LOAD TPS : 37.40    LOAD MAP : 10.00    TPS : 1.60  MAP : 0.85  Final LOAD : 23.70
LOAD TPS : 37.40    LOAD MAP : 17.14    TPS : 1.60  MAP : 0.95  Final LOAD : 27.27
LOAD TPS : 37.40    LOAD MAP : 24.29    TPS : 1.60  MAP : 1.05  Final LOAD : 30.84
LOAD TPS : 37.40    LOAD MAP : 31.43    TPS : 1.60  MAP : 1.15  Final LOAD : 34.41
LOAD TPS : 37.40    LOAD MAP : 38.57    TPS : 1.60  MAP : 1.25  Final LOAD : 37.99
LOAD TPS : 37.40    LOAD MAP : 45.71    TPS : 1.60  MAP : 1.35  Final LOAD : 41.56
LOAD TPS : 37.40    LOAD MAP : 52.86    TPS : 1.60  MAP : 1.45  Final LOAD : 45.13
LOAD TPS : 37.40    LOAD MAP : 60.00    TPS : 1.60  MAP : 1.55  Final LOAD : 48.70
LOAD TPS : 37.40    LOAD MAP : 67.14    TPS : 1.60  MAP : 1.65  Final LOAD : 52.27
LOAD TPS : 37.40    LOAD MAP : 74.29    TPS : 1.60  MAP : 1.75  Final LOAD : 55.84
LOAD TPS : 37.40    LOAD MAP : 81.43    TPS : 1.60  MAP : 1.85  Final LOAD : 59.41
LOAD TPS : 37.40    LOAD MAP : 85.00    TPS : 1.60  MAP : 1.90  Final LOAD : 61.20
LOAD TPS : 43.00    LOAD MAP : 10.00    TPS : 2.00  MAP : 0.85  Final LOAD : 26.50
LOAD TPS : 43.00    LOAD MAP : 17.14    TPS : 2.00  MAP : 0.95  Final LOAD : 30.07
LOAD TPS : 43.00    LOAD MAP : 24.29    TPS : 2.00  MAP : 1.05  Final LOAD : 33.64
LOAD TPS : 43.00    LOAD MAP : 31.43    TPS : 2.00  MAP : 1.15  Final LOAD : 37.21
LOAD TPS : 43.00    LOAD MAP : 38.57    TPS : 2.00  MAP : 1.25  Final LOAD : 40.79
LOAD TPS : 43.00    LOAD MAP : 45.71    TPS : 2.00  MAP : 1.35  Final LOAD : 44.36
LOAD TPS : 43.00    LOAD MAP : 52.86    TPS : 2.00  MAP : 1.45  Final LOAD : 47.93
LOAD TPS : 43.00    LOAD MAP : 60.00    TPS : 2.00  MAP : 1.55  Final LOAD : 51.50
LOAD TPS : 43.00    LOAD MAP : 67.14    TPS : 2.00  MAP : 1.65  Final LOAD : 55.07
LOAD TPS : 43.00    LOAD MAP : 74.29    TPS : 2.00  MAP : 1.75  Final LOAD : 58.64
LOAD TPS : 43.00    LOAD MAP : 81.43    TPS : 2.00  MAP : 1.85  Final LOAD : 62.21
LOAD TPS : 43.00    LOAD MAP : 85.00    TPS : 2.00  MAP : 1.90  Final LOAD : 64.00
LOAD TPS : 48.60    LOAD MAP : 10.00    TPS : 2.40  MAP : 0.85  Final LOAD : 29.30
LOAD TPS : 48.60    LOAD MAP : 17.14    TPS : 2.40  MAP : 0.95  Final LOAD : 32.87
LOAD TPS : 48.60    LOAD MAP : 24.29    TPS : 2.40  MAP : 1.05  Final LOAD : 36.44
LOAD TPS : 48.60    LOAD MAP : 31.43    TPS : 2.40  MAP : 1.15  Final LOAD : 40.01
LOAD TPS : 48.60    LOAD MAP : 38.57    TPS : 2.40  MAP : 1.25  Final LOAD : 43.59
LOAD TPS : 48.60    LOAD MAP : 45.71    TPS : 2.40  MAP : 1.35  Final LOAD : 47.16
LOAD TPS : 48.60    LOAD MAP : 52.86    TPS : 2.40  MAP : 1.45  Final LOAD : 50.73
LOAD TPS : 48.60    LOAD MAP : 60.00    TPS : 2.40  MAP : 1.55  Final LOAD : 54.30
LOAD TPS : 48.60    LOAD MAP : 67.14    TPS : 2.40  MAP : 1.65  Final LOAD : 57.87
LOAD TPS : 48.60    LOAD MAP : 74.29    TPS : 2.40  MAP : 1.75  Final LOAD : 61.44
LOAD TPS : 48.60    LOAD MAP : 81.43    TPS : 2.40  MAP : 1.85  Final LOAD : 65.01
LOAD TPS : 48.60    LOAD MAP : 85.00    TPS : 2.40  MAP : 1.90  Final LOAD : 66.80
LOAD TPS : 54.20    LOAD MAP : 10.00    TPS : 2.80  MAP : 0.85  Final LOAD : 32.10
LOAD TPS : 54.20    LOAD MAP : 17.14    TPS : 2.80  MAP : 0.95  Final LOAD : 35.67
LOAD TPS : 54.20    LOAD MAP : 24.29    TPS : 2.80  MAP : 1.05  Final LOAD : 39.24
LOAD TPS : 54.20    LOAD MAP : 31.43    TPS : 2.80  MAP : 1.15  Final LOAD : 42.81
LOAD TPS : 54.20    LOAD MAP : 38.57    TPS : 2.80  MAP : 1.25  Final LOAD : 46.39
LOAD TPS : 54.20    LOAD MAP : 45.71    TPS : 2.80  MAP : 1.35  Final LOAD : 49.96
LOAD TPS : 54.20    LOAD MAP : 52.86    TPS : 2.80  MAP : 1.45  Final LOAD : 53.53
LOAD TPS : 54.20    LOAD MAP : 60.00    TPS : 2.80  MAP : 1.55  Final LOAD : 57.10
LOAD TPS : 54.20    LOAD MAP : 67.14    TPS : 2.80  MAP : 1.65  Final LOAD : 60.67
LOAD TPS : 54.20    LOAD MAP : 74.29    TPS : 2.80  MAP : 1.75  Final LOAD : 64.24
LOAD TPS : 54.20    LOAD MAP : 81.43    TPS : 2.80  MAP : 1.85  Final LOAD : 67.81
LOAD TPS : 54.20    LOAD MAP : 85.00    TPS : 2.80  MAP : 1.90  Final LOAD : 69.60
LOAD TPS : 59.80    LOAD MAP : 10.00    TPS : 3.20  MAP : 0.85  Final LOAD : 34.90
LOAD TPS : 59.80    LOAD MAP : 17.14    TPS : 3.20  MAP : 0.95  Final LOAD : 38.47
LOAD TPS : 59.80    LOAD MAP : 24.29    TPS : 3.20  MAP : 1.05  Final LOAD : 42.04
LOAD TPS : 59.80    LOAD MAP : 31.43    TPS : 3.20  MAP : 1.15  Final LOAD : 45.61
LOAD TPS : 59.80    LOAD MAP : 38.57    TPS : 3.20  MAP : 1.25  Final LOAD : 49.19
LOAD TPS : 59.80    LOAD MAP : 45.71    TPS : 3.20  MAP : 1.35  Final LOAD : 52.76
LOAD TPS : 59.80    LOAD MAP : 52.86    TPS : 3.20  MAP : 1.45  Final LOAD : 56.33
LOAD TPS : 59.80    LOAD MAP : 60.00    TPS : 3.20  MAP : 1.55  Final LOAD : 59.90
LOAD TPS : 59.80    LOAD MAP : 67.14    TPS : 3.20  MAP : 1.65  Final LOAD : 63.47
LOAD TPS : 59.80    LOAD MAP : 74.29    TPS : 3.20  MAP : 1.75  Final LOAD : 67.04
LOAD TPS : 59.80    LOAD MAP : 81.43    TPS : 3.20  MAP : 1.85  Final LOAD : 70.61
LOAD TPS : 59.80    LOAD MAP : 85.00    TPS : 3.20  MAP : 1.90  Final LOAD : 72.40
LOAD TPS : 65.40    LOAD MAP : 10.00    TPS : 3.60  MAP : 0.85  Final LOAD : 37.70
LOAD TPS : 65.40    LOAD MAP : 17.14    TPS : 3.60  MAP : 0.95  Final LOAD : 41.27
LOAD TPS : 65.40    LOAD MAP : 24.29    TPS : 3.60  MAP : 1.05  Final LOAD : 44.84
LOAD TPS : 65.40    LOAD MAP : 31.43    TPS : 3.60  MAP : 1.15  Final LOAD : 48.41
LOAD TPS : 65.40    LOAD MAP : 38.57    TPS : 3.60  MAP : 1.25  Final LOAD : 51.99
LOAD TPS : 65.40    LOAD MAP : 45.71    TPS : 3.60  MAP : 1.35  Final LOAD : 55.56
LOAD TPS : 65.40    LOAD MAP : 52.86    TPS : 3.60  MAP : 1.45  Final LOAD : 59.13
LOAD TPS : 65.40    LOAD MAP : 60.00    TPS : 3.60  MAP : 1.55  Final LOAD : 62.70
LOAD TPS : 65.40    LOAD MAP : 67.14    TPS : 3.60  MAP : 1.65  Final LOAD : 66.27
LOAD TPS : 65.40    LOAD MAP : 74.29    TPS : 3.60  MAP : 1.75  Final LOAD : 69.84
LOAD TPS : 65.40    LOAD MAP : 81.43    TPS : 3.60  MAP : 1.85  Final LOAD : 73.41
LOAD TPS : 65.40    LOAD MAP : 85.00    TPS : 3.60  MAP : 1.90  Final LOAD : 75.20
LOAD TPS : 71.00    LOAD MAP : 10.00    TPS : 4.00  MAP : 0.85  Final LOAD : 40.50
LOAD TPS : 71.00    LOAD MAP : 17.14    TPS : 4.00  MAP : 0.95  Final LOAD : 44.07
LOAD TPS : 71.00    LOAD MAP : 24.29    TPS : 4.00  MAP : 1.05  Final LOAD : 47.64
LOAD TPS : 71.00    LOAD MAP : 31.43    TPS : 4.00  MAP : 1.15  Final LOAD : 51.21
LOAD TPS : 71.00    LOAD MAP : 38.57    TPS : 4.00  MAP : 1.25  Final LOAD : 54.79
LOAD TPS : 71.00    LOAD MAP : 45.71    TPS : 4.00  MAP : 1.35  Final LOAD : 58.36
LOAD TPS : 71.00    LOAD MAP : 52.86    TPS : 4.00  MAP : 1.45  Final LOAD : 61.93
LOAD TPS : 71.00    LOAD MAP : 60.00    TPS : 4.00  MAP : 1.55  Final LOAD : 65.50
LOAD TPS : 71.00    LOAD MAP : 67.14    TPS : 4.00  MAP : 1.65  Final LOAD : 69.07
LOAD TPS : 71.00    LOAD MAP : 74.29    TPS : 4.00  MAP : 1.75  Final LOAD : 72.64
LOAD TPS : 71.00    LOAD MAP : 81.43    TPS : 4.00  MAP : 1.85  Final LOAD : 76.21
LOAD TPS : 71.00    LOAD MAP : 85.00    TPS : 4.00  MAP : 1.90  Final LOAD : 78.00
LOAD TPS : 76.60    LOAD MAP : 10.00    TPS : 4.40  MAP : 0.85  Final LOAD : 43.30
LOAD TPS : 76.60    LOAD MAP : 17.14    TPS : 4.40  MAP : 0.95  Final LOAD : 46.87
LOAD TPS : 76.60    LOAD MAP : 24.29    TPS : 4.40  MAP : 1.05  Final LOAD : 50.44
LOAD TPS : 76.60    LOAD MAP : 31.43    TPS : 4.40  MAP : 1.15  Final LOAD : 54.01
LOAD TPS : 76.60    LOAD MAP : 38.57    TPS : 4.40  MAP : 1.25  Final LOAD : 57.59
LOAD TPS : 76.60    LOAD MAP : 45.71    TPS : 4.40  MAP : 1.35  Final LOAD : 61.16
LOAD TPS : 76.60    LOAD MAP : 52.86    TPS : 4.40  MAP : 1.45  Final LOAD : 64.73
LOAD TPS : 76.60    LOAD MAP : 60.00    TPS : 4.40  MAP : 1.55  Final LOAD : 68.30
LOAD TPS : 76.60    LOAD MAP : 67.14    TPS : 4.40  MAP : 1.65  Final LOAD : 71.87
LOAD TPS : 76.60    LOAD MAP : 74.29    TPS : 4.40  MAP : 1.75  Final LOAD : 75.44
LOAD TPS : 76.60    LOAD MAP : 81.43    TPS : 4.40  MAP : 1.85  Final LOAD : 79.01
LOAD TPS : 76.60    LOAD MAP : 85.00    TPS : 4.40  MAP : 1.90  Final LOAD : 80.80
LOAD TPS : 82.20    LOAD MAP : 10.00    TPS : 4.80  MAP : 0.85  Final LOAD : 46.10
LOAD TPS : 82.20    LOAD MAP : 17.14    TPS : 4.80  MAP : 0.95  Final LOAD : 49.67
LOAD TPS : 82.20    LOAD MAP : 24.29    TPS : 4.80  MAP : 1.05  Final LOAD : 53.24
LOAD TPS : 82.20    LOAD MAP : 31.43    TPS : 4.80  MAP : 1.15  Final LOAD : 56.81
LOAD TPS : 82.20    LOAD MAP : 38.57    TPS : 4.80  MAP : 1.25  Final LOAD : 60.39
LOAD TPS : 82.20    LOAD MAP : 45.71    TPS : 4.80  MAP : 1.35  Final LOAD : 63.96
LOAD TPS : 82.20    LOAD MAP : 52.86    TPS : 4.80  MAP : 1.45  Final LOAD : 67.53
LOAD TPS : 82.20    LOAD MAP : 60.00    TPS : 4.80  MAP : 1.55  Final LOAD : 71.10
LOAD TPS : 82.20    LOAD MAP : 67.14    TPS : 4.80  MAP : 1.65  Final LOAD : 74.67
LOAD TPS : 82.20    LOAD MAP : 74.29    TPS : 4.80  MAP : 1.75  Final LOAD : 78.24
LOAD TPS : 82.20    LOAD MAP : 81.43    TPS : 4.80  MAP : 1.85  Final LOAD : 81.81
LOAD TPS : 82.20    LOAD MAP : 85.00    TPS : 4.80  MAP : 1.90  Final LOAD : 83.60
LOAD TPS : 85.00    LOAD MAP : 10.00    TPS : 5.00  MAP : 0.85  Final LOAD : 47.50
LOAD TPS : 85.00    LOAD MAP : 17.14    TPS : 5.00  MAP : 0.95  Final LOAD : 51.07
LOAD TPS : 85.00    LOAD MAP : 24.29    TPS : 5.00  MAP : 1.05  Final LOAD : 54.64
LOAD TPS : 85.00    LOAD MAP : 31.43    TPS : 5.00  MAP : 1.15  Final LOAD : 58.21
LOAD TPS : 85.00    LOAD MAP : 38.57    TPS : 5.00  MAP : 1.25  Final LOAD : 61.79
LOAD TPS : 85.00    LOAD MAP : 45.71    TPS : 5.00  MAP : 1.35  Final LOAD : 65.36
LOAD TPS : 85.00    LOAD MAP : 52.86    TPS : 5.00  MAP : 1.45  Final LOAD : 68.93
LOAD TPS : 85.00    LOAD MAP : 60.00    TPS : 5.00  MAP : 1.55  Final LOAD : 72.50
LOAD TPS : 85.00    LOAD MAP : 67.14    TPS : 5.00  MAP : 1.65  Final LOAD : 76.07
LOAD TPS : 85.00    LOAD MAP : 74.29    TPS : 5.00  MAP : 1.75  Final LOAD : 79.64
LOAD TPS : 85.00    LOAD MAP : 81.43    TPS : 5.00  MAP : 1.85  Final LOAD : 83.21
LOAD TPS : 85.00    LOAD MAP : 85.00    TPS : 5.00  MAP : 1.90  Final LOAD : 85.00

```

NOTE : Here, I'm not providing all serial monitor output. Just needed part of OUTPUT here displayed.

# Answer
Here, this is modified code which provide result which I want.

```
float TPS_MIN = 0.00;
float TPS_MAX = 5.00;

float MAP_MIN = 0.85;
float MAP_MAX = 1.90;

int LOAD_MIN = 2;
int LOAD_MAX = 100;

int RPM_MIN = 400;
int RPM_MAX = 6000;

float LOAD_MIN_TPS_MIN = 2.00;
float LOAD_MAX_TPS_MIN = 10.00;

float LOAD_MIN_TPS_MAX = 15.00;
float LOAD_MAX_TPS_MAX = 85.00;

float LOAD_MIN_MAP_MIN = 2.00;
float LOAD_MAX_MAP_MIN = 15.00;

float LOAD_MIN_MAP_MAX = 10.00;
float LOAD_MAX_MAP_MAX = 85.00;

float injTime_MIN_LOAD_MIN = 4.00;
float injTime_MAX_LOAD_MIN = 4.60;

float injTime_MIN_LOAD_MAX = 8.06;
float injTime_MAX_LOAD_MAX = 14.86;

float injTime_MIN_RPM_MIN = 4.00;
float injTime_MAX_RPM_MIN = 8.06;

float injTime_MIN_RPM_MAX = 4.60;
float injTime_MAX_RPM_MAX = 14.86;

float mTPSmin;
float mTPSmax;
float mMAPmin;
float mMAPmax;

float yTPSmin;
float yTPSmax;
float yMAPmin;
float yMAPmax;

float mTPS;
float mMAP;

float yTPS;
float yMAP;

float LOAD;

float TPS, MAP;

float mLOADmin;
float mLOADmax;
float mRPMmin;
float mRPMmax;

float yLOADmin;
float yLOADmax;
float yRPMmin;
float yRPMmax;

float mLOAD;
float mRPM;

float yLOAD;
float yRPM;

float yInjTime;

int RPM;

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

void loop()
{
    TPS = analogRead(A0) * (5.0 / 1023.0);
    MAP = analogRead(A1) * (1.90 / 1023.0);
    RPM = analogRead(A2) * (6000 / 1023.0);

    mTPSmin = (LOAD_MAX_TPS_MIN - LOAD_MIN_TPS_MIN) / (TPS_MAX - TPS_MIN);

    Serial.print("mTPSmin : ");
    Serial.println(mTPSmin);

    yTPSmin = mTPSmin * (TPS - TPS_MIN) + LOAD_MIN_TPS_MIN;

    Serial.print("TPS : ");
    Serial.print(TPS);
    Serial.print("\t");
    Serial.print("LOAD : ");
    Serial.println(yTPSmin);

    mTPSmax = (LOAD_MAX_TPS_MAX - LOAD_MIN_TPS_MAX) / (TPS_MAX - TPS_MIN);

    Serial.print("mTPSmax : ");
    Serial.println(mTPSmax);

    yTPSmax = mTPSmax * (TPS - TPS_MIN) + LOAD_MIN_TPS_MAX;

    Serial.print("TPS : ");
    Serial.print(TPS);
    Serial.print("\t");
    Serial.print("LOAD : ");
    Serial.println(yTPSmax);

    mMAPmin = (LOAD_MAX_MAP_MIN - LOAD_MIN_MAP_MIN) / (MAP_MAX - MAP_MIN);

    Serial.print("mMAPmin : ");
    Serial.println(mMAPmin);

    yMAPmin = mMAPmin * (MAP - MAP_MIN) + LOAD_MIN_MAP_MIN;

    Serial.print("MAP : ");
    Serial.print(MAP);
    Serial.print("\t");
    Serial.print("LOAD : ");
    Serial.println(yMAPmin);

    mMAPmax = (LOAD_MAX_MAP_MAX - LOAD_MIN_MAP_MAX) / (MAP_MAX - MAP_MIN);

    Serial.print("mMAPmax : ");
    Serial.println(mMAPmax);

    yMAPmax = mMAPmax * (MAP - MAP_MIN) + LOAD_MIN_MAP_MAX;

    Serial.print("MAP : ");
    Serial.print(MAP);
    Serial.print("\t");
    Serial.print("LOAD : ");
    Serial.println(yMAPmax);

    mTPS = (yMAPmax - yMAPmin) / (TPS_MAX - TPS_MIN);

    Serial.print("mTPS : ");
    Serial.println(mTPS);

    yTPS = mTPS * (TPS - TPS_MIN) + yMAPmin;

    Serial.print("TPS : ");
    Serial.print(TPS);
    Serial.print("\t");
    Serial.print("LOAD : ");
    Serial.println(yTPS);

    mMAP = (yTPSmax - yTPSmin) / (MAP_MAX - MAP_MIN);

    Serial.print("mMAP : ");
    Serial.println(mMAP);

    yMAP = mMAP * (MAP - MAP_MIN) + yTPSmin;

    Serial.print("MAP : ");
    Serial.print(MAP);
    Serial.print("\t");
    Serial.print("LOAD : ");
    Serial.println(yMAP);

    LOAD = (yTPS + yMAP) / 2;
    Serial.print("Final LOAD : ");
    Serial.println(LOAD);

    mLOADmin = (injTime_MAX_LOAD_MIN - injTime_MIN_LOAD_MIN) / (LOAD_MAX - LOAD_MIN);

    Serial.print("mLOADmin : ");
    Serial.println(mLOADmin);

    yLOADmin = mLOADmin * (LOAD - LOAD_MIN) + injTime_MIN_LOAD_MIN;

    Serial.print("LOAD : ");
    Serial.print(LOAD);
    Serial.print("\t");
    Serial.print("injTime : ");
    Serial.println(yLOADmin);

    mLOADmax = (injTime_MAX_LOAD_MAX - injTime_MIN_LOAD_MAX) / (LOAD_MAX - LOAD_MIN);

    Serial.print("mLOADmax : ");
    Serial.println(mLOADmax);

    yLOADmax = mLOADmax * (LOAD - LOAD_MIN) + injTime_MIN_LOAD_MAX;

    Serial.print("LOAD : ");
    Serial.print(LOAD);
    Serial.print("\t");
    Serial.print("injTime : ");
    Serial.println(yLOADmax);

    mRPMmin = (injTime_MAX_RPM_MIN - injTime_MIN_RPM_MIN) / (RPM_MAX - RPM_MIN);

    Serial.print("mRPMmin : ");
    Serial.println(mRPMmin);

    yRPMmin = mRPMmin * (RPM - RPM_MIN) + injTime_MIN_RPM_MIN;

    Serial.print("RPM : ");
    Serial.print(RPM);
    Serial.print("\t");
    Serial.print("injTime : ");
    Serial.println(yRPMmin);

    mRPMmax = (injTime_MAX_RPM_MAX - injTime_MIN_RPM_MAX) / (RPM_MAX - RPM_MIN);

    Serial.print("mRPMmax : ");
    Serial.println(mRPMmax);

    yRPMmax = mRPMmax * (RPM - RPM_MIN) + injTime_MIN_RPM_MAX;

    Serial.print("RPM : ");
    Serial.print(RPM);
    Serial.print("\t");
    Serial.print("injTime : ");
    Serial.println(yRPMmax);

    mLOAD = (yRPMmax - yRPMmin) / (LOAD_MAX - LOAD_MIN);

    Serial.print("mLOAD : ");
    Serial.println(mLOAD);

    yLOAD = mLOAD * (LOAD - LOAD_MIN) + yRPMmin;

    Serial.print("LOAD : ");
    Serial.print(LOAD);
    Serial.print("\t");
    Serial.print("injTime : ");
    Serial.println(yLOAD);

    mRPM = (yLOADmax - yLOADmin) / (RPM_MAX - RPM_MIN);

    Serial.print("mRPM : ");
    Serial.println(mRPM);

    yRPM = mRPM * (RPM - RPM_MIN) + yLOADmin;

    Serial.print("RPM : ");
    Serial.print(RPM);
    Serial.print("\t");
    Serial.print("injTime : ");
    Serial.println(yRPM);

    yInjTime = (yLOAD + yRPM) / 2;
    Serial.print("Final injTime : ");
    Serial.println(yInjTime);

    delay(1000000);
}

```
> 1 votes

---
Tags: arduino-uno, programming
---


# Question
Title: What is the proper way to implement PID?
I'm having some trouble conceptualizing how to go about implementing PID into my drone. There are a few ways I'm thinking about implementing the pipeline:

* Having one PID Object for each of the six motors.
* Having one PID Object for each axis.

How I would implement PIDs on a per-motor basis?

How I would implement PIDs on a per-axis basis?

I'm guessing that the second one will be the best course of action, as it can all be put into its own loop, where the PID data will be available on-demand, as opposed to calculating it on the spot. It is object-oriented, and runs in the background.

The first one has its appeals, too. It eliminates some of the calculations needed in order to find the actual value. It is procedural, and very straightforward and performs on the spot.

What do you guys think?

# Answer
> 3 votes
Each unique variable you want control over should have a single pid loop, and each loop should only ever stretch across one "order" of time.

For example, to control the craft's roll rate, you should have one PID loop that takes the target roll rate and outputs the controlled roll torque value, which gets transformed somehow into motor accelerations. The trig weights for that part can be precalculated so it doesn't have to happen at runtime.

To control the craft's roll rotational position, you would need one PID loop that takes the target roll position and outputs the target roll velocity, that target roll velocity then becomes the setpoint for the roll-velocity pid loop.

I don't see why each motor would need its own PID loop unless you are measuring the actual thrust each motor produces. If you did measure each motor's thrust their pid loops would still come after the target torque value were calculated. The target torque PID calculations don't need to know about what motors exist or where they are located.

I may not be understanding the intention of your diagrams or what "order" the PID loops are in, so feel free to comment with clarifications. This is complicated stuff.

Its also worth noting that the actual implementation pid often has some features that don't appear in theoretical pid loops like integral windup prevention. You also need a way to either call them at exactly the same interval each time, or accurately keep track of the time delta since the last update. You may want to take the derivative of the process variable only, not the error, so you don't observe setpoint changes in the D term; you could also "outsource" the derivative term if you IMU has a better calculation of it (like the raw gyroscope values).

# Answer
> 1 votes
I will give a generic C-answer to it:

1) figure out what parameters / variables involved in a PID control loop; 2) structure those parameters / variables into a struct; 3) pass that struct to a common set of PID algorithm. 4) done.

with this approach, the algorithm is only implemented once and the can be used / reused as many times as you want.

---
Tags: arduino-due, remote-control, code-optimization, pid, drone
---


# Question
Title: How to analyse audio and to affect source?
I want to use the audio from my PC and have it going to the speakers and Arduino for some lighting effects. This project is a bit of a struggle because I don't know what the best way of analysing audio is. So for the lights I only want bass frequencies to affect the lights.

# Answer
I have actually just finished a project doing exactly that. I used a frequency analyser chip called an MSGEQ7 (Available from Sparksfun), here's the datasheet.

https://www.sparkfun.com/datasheets/Components/General/MSGEQ7.pdf

These little things are really easy to use. Give me a shout if you would like any help with it such as coding or wiring.
> 1 votes

# Answer
There's many ways of achieving what you want - some in software, some in hardware.

Since you are only interested in the lower frequencies this opens up the possibility of a *low pass filter* \- either a hardware one, or a software one. The simplest hardware one is just a resistor in series followed by a capacitor in parallel:

simulate this circuit – Schematic created using CircuitLab

(representative component values: increase capacitance and/or resistance to decrease frequency)

Doing it in software is just as simple: you sample at a regular frequency through whatever means are suitable (there's plenty of resources for sampling at a specific frequency on the Arduino - google them), then you average samples together to remove higher frequency components. The more you average the lower your cut-off frequency. Each time you average you halve the frequency range. Note that the frequency range is already *half* the sample frequency.

For instance: if you sample at 8kHz (say 512 samples) you get a 0-4kHz frequency range in your sample set. Averaging each pair of samples (which results in 256 samples) gives you a 0-2kHz frequency range. Averaging again, for 128 samples, gives you 0-1kHz. Average again, for 64 samples, gives you 0-500Hz. Again, 32 samples, 0-250Hz. Keep going, until you have your desired cut-off frequency.

Then you can scan the sample set for the maximum and minimum and take that as your peak amplitude for the sample set.

You have to make sure that your sample frequency is at least twice the highest frequency you are interested in (preferably more so that you can do some averaging), and that your sample set is large enough, at the chosen sample frequency, to contain at least one full cycle of the lowest frequency you are interested in. For instance, at 8kHz sample frequency, if you are interested in responding to frequencies down to 50Hz, you need to sample for at least (1/50) 20ms, which at 8kHz means (8000 samples per second times 0.02 seconds) 160 samples. Since it's usually better to work with powers of 2 that means 256 samples is the next biggest "slot" that would do.

If you want to access more information about the actual frequency content of your sample set so as to light different LEDs when different frequency components are in the signal you need a *Fast Fourier Transform* (FFT). This converts the sample set into a collection of *buckets* (exactly half the buckets as you have samples) each representing a portion of the frequency range of your sample set. For 256 samples that gives you 128 buckets, each representing 1/128 of your total frequency range. So at 8000 samples per second, or a 4kHz frequency range, each bucket gives you a 31.25Hz resolution.

The problem with FFT is it is computationally expensive. It also needs more memory than simple averaging.

Depending on the algorithm you use, you will probably find you need 16 bit samples, and each sample should be in the form of a "real" and "imaginary" component, amounting to 32 bits per sample. Most algorithms require powers-of-two for the number of samples. For 256 samples that means you are using 1024kB of memory just for sample storage and processing, which is half of what the Uno has. You certainly won't be able to go over 256 samples on an Uno (the next step up is 512, which would want to use the entire memory leaving no room for any other variables).

There are two basic forms of algorithms for FFT: floating point, and integer. The floating point variant is great on a CPU that has an FPU with it to do the number crunching, but on an Arduino that just isn't possible. So the floating point version would take a massive amount of time to process making your results incredibly jittery. Far from desirable. So you need to find the integer version (one example) which runs much faster.

Calculating an FFT is done in two parts: first it calculates the real and imaginary components from the sample set, and second it converts those two components into a single vector, the length of which is the amplitude of the bucket. Whether or not you are using the integer FFT algorithm that second phase is going to be slow. It involves a square root (it's basically pythagoras: `sqrt((r*r) + (i*i));`) and that is almost always slow. Getting that to work fast on an Arduino is not at all easy. You can sacrifice accuracy for speed though and write your own square root approximation routine (as I have done before for 3D vector manipulation in a graphics library):

```
float quick_sqrt(float number) {
    int32_t i;
    float x2, y2;
    const float threehalfs = 1.5F;

    x2 = number * 0.5F;
    y2  = number;
    i  = * ( long * ) &y2;
    i  = 0x5f3759df - ( i >> 1 );
    y2  = * ( float * ) &i;
    y2  = y2 * ( threehalfs - ( x2 * y2 * y2 ) );

    return 1.0/y2;
}

```

That uses a few tricks to do with the way a floating point number is stored to create an approximation of the square root.

With all that you can see that the Arduino can do FFT, but it's not the best solution for FFT. Ideally you need a faster, more powerful, chip with more memory (personally I use a PIC32MZ "EF" variant: 200MHz, 512kB RAM, FPU).
> 0 votes

---
Tags: led, audio
---


# Question
Title: Fastest communication between Arduino and PC
I am using an Arduino 2 which collects data from a set of microphones and stores it in an array of unsigned short of 40000 elements and sends them to the PC via Serial USB.

It is working but I'd like to obtain more speed without any errors.

Can you suggest me the best way to do it? Even changing communication.

Thank you

# Answer
Switch to using SerialUSB instead and use the other USB port. The baud rate is meaningless then - it runs at the speed of the USB port, which is a lot faster than serial (Linux reports it as 480Mbps, though I can't see an 84MHz chip doing that...).

```
void setup() {
    SerialUSB.begin(115200); // The number is irrelevant but it needs something in there
}

void loop() {
    SerialUSB.println(millis());
    delay(100);
}

```

For greater throughput you could devise some packet-based binary protocol to optimize your data flow to use less bytes.
> 3 votes

# Answer
SPI: technically no upper limit so long as both parties can keep up and the wires are good enough. Mbps easily doable.
> 1 votes

---
Tags: serial, arduino-due, array
---


# Question
Title: Playing WAV file from Arduino Uno using Ethernet R3 Shield
I'm trying to start a project where I have a 6 sec recording (wav file: 8 bit, 8 or 16 kHz, mono) on a micro-SD card and want to play it through my Arduino Uno on an 8 Ohm, 0.1 W speaker. I've looked at many different forums and threads for how to do this. One that continually comes up is this link, but this is for the Due and I can't figure out how to adapt for the Uno.

The important bit is I am using an Ethernet R3 shield which has a built in micro-SD card reader. Much of the code and tutorials I found use the TMRpcm library, setting the speaker pin to 9, the SDChipSelectPin to 4, with various wire connection geometries depending on which tutorial you read. I really need help trying to figure out how the wiring is supposed to go. I, honestly, do not understand what's going on and am hoping someone will take the time and can explain this pretty pedagogically. Currently, no matter what I try, I just hear high-pitched static or fast periodic noises.

# Answer
> 1 votes
Your Arduino UNO won't play any wave file the way you're expecting. There's not enough processing power to do that. In order to play audio using small MCUs such as AVR (or PIC for example) you must use the BTC algorithm. Please, check this out : http://www.radanpro.com/Radan2400/mikrokontroleri/How%20to%20make%20sound%20with%20a%20PIC%20chip.htm and download the software which can convert your wave file into an array which can be then played by Arduino using a BTC algorithm. Schematics on how to place reistors and speakers to match impedance are provided and suggested on the software as well.

---
Tags: arduino-uno, speaker
---


# Question
Title: Setting a pointer to NULL in Arduino library - error: ‘NULL’ was not declared in this scope
I am writing my own library for using with my Arduino. In my code, if I set a pointer I have declared to `NULL`, such as

```
int *ptr=NULL;

```

I get the error

```
error: ‘NULL’ was not declared in this scope

```

I need to initialize it to `NULL` as I am using pointers to implement a list.

If I use `NULL` directly in the program in the IDE, I do not get this error. This seems to be happening only when it is a part of the library code.

How do I correct this? Is there any alternative keyword to use? Or do I have to include some library?

Thank you.

# Answer
> I am writing my own library for using with my Arduino.

You should really include Arduino.h, i.e.

```
#include <Arduino.h>

```

Not only will that define `NULL` for you, but you also get the other standard Arduino functions like `digitalRead`, pin number declarations, and various useful macros.
> 3 votes

# Answer
You should make sure your header includes the `stddef.h` header, which holds all these standard definitions (hence its name):

```
#include <stddef.h>

```
> 2 votes

---
Tags: programming, library, pointer
---


title: Stepper and Line tracker

text:
# Question
Title: Stepper and Line tracker
I am making a program which will use stepper motors and a line tracking sensor. The idea is that when the linetracker detects a black surface both steppers must move forward, and when the linetrackers is not detecting black surface it should scan the surface for a black surface.

I made some code which makes the robot move forward if the linetracker has a set value. The problem is that when I implement the code for the line-tracker. My steppers are going to run very laggy probably because the arduino is constantly scanning if the value of the linetracker is below 500.

My question is, is there a way to program the line tracker without having it interfere on my stepper motors? (The stepper motors run smooth without the linetracker)

```
#include <RedBot.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
//Code voor de LCD
#define I2C_ADDR       0x3F // Define I2C Address (use i2c scanner if necessary)
#define BACKLIGHT_PIN  3
#define En_pin         2
#define Rw_pin         1
#define Rs_pin         0
#define D4_pin         4
#define D5_pin         5
#define D6_pin         6
#define D7_pin         7
#define LED_OFF        0

#define LED_ON         1
//Hier worden de eigen functies gemaakt door HEX code
uint8_t battery_1[8]=   {0xe,0x1b,0x11,0x11,0x11,0x11,0x11,0x1f};
uint8_t battery_2[8]=   {0xe,0x1b,0x11,0x11,0x11,0x11,0x1f,0x1f};
uint8_t battery_3[8]=   {0xe,0x1b,0x11,0x11,0x11,0x1f,0x1f,0x1f};
uint8_t battery_4[8]=   {0xe,0x1b,0x11,0x11,0x1f,0x1f,0x1f,0x1f};
uint8_t battery_5[8]=   {0xe,0x1b,0x11,0x1f,0x1f,0x1f,0x1f,0x1f};
uint8_t battery_6[8]=   {0xe,0x1b,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f};
uint8_t battery_7[8]=   {0xe,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f,0x1f};
LiquidCrystal_I2C lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin);

RedBotSensor left_sen    =    RedBotSensor(A3);
RedBotSensor right_sen   =    RedBotSensor(A2);
int lineStandard         =    800;

void setup()
{
  scherm();
  //stepper 1
  pinMode(13,OUTPUT);   // Step
  pinMode(12,OUTPUT);   // Dir
  //stepper 2
  pinMode(11,OUTPUT);   //Step 2
  pinMode(10,OUTPUT);   //Dir 2
  Serial.begin(9600);
  Serial.println("IR Sensor Readings:: ");
  //delay(500);
}

void loop()
{
  Serial.print(left_sen.read());
  Serial.print("\t");
  Serial.print(right_sen.read());
  Serial.println();

  if(right_sen.read() > lineStandard)
    {
      left();
    }

  else if(left_sen.read() > lineStandard)
    {
      right();
    }

  if((left_sen.read() > lineStandard) && (right_sen.read() > lineStandard) )
    {
      Stop ();
    }

  else
    {
      forward();
    }
}

void right()
{
  //stepper 1
  digitalWrite(13,HIGH);
  delayMicroseconds(1500);
  digitalWrite(13,LOW);
  delayMicroseconds(1500);
  //stepper 2
  digitalWrite(11,LOW);
  delayMicroseconds(1500);
  //Oranje lampje, rechter kant
  //digitalWrite(3,HIGH);
}
void Stop ()
{
  digitalWrite(13, LOW);
  delay(1500);
  digitalWrite(11, LOW);
  delay(1500);
  //Rood lampje aansturen
  //digitalWrite(2,HIGH);
}
void left()
{
  //stepper 1
  digitalWrite(11,HIGH);
  delayMicroseconds(1500);
  digitalWrite(11,LOW);
  delayMicroseconds(1500);
  //stepper 2
  digitalWrite(13,LOW);
  delayMicroseconds(1500);
  //Oranje lampje, linker kant
  //digitalWrite(4,HIGH);
}
void forward()
{
  //stepper 1
  digitalWrite(13,HIGH);
  delayMicroseconds(1500);
  digitalWrite(13,LOW);
  delayMicroseconds(1500);
  //stepper 2
  digitalWrite(11,HIGH);
  delayMicroseconds(1500);
  digitalWrite(11,LOW);
  delayMicroseconds(1500);
  //Groen lampje sturen
  //digitalWrite(1,HIGH);
}

void scherm()
{
  lcd.begin(16,2);
  lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);
  lcd.setBacklight(LED_ON);
  //Hier worden de eigen symbolen benoemd
  lcd.createChar(1, battery_1);
  lcd.createChar(2, battery_2);
  lcd.createChar(3, battery_3);
  lcd.createChar(4, battery_4);
  lcd.createChar(5, battery_5);
  lcd.createChar(6, battery_6);
  lcd.createChar(7, battery_7);
  lcd.home();
  lcd.print("Batterij Status");
  lcd.setCursor(0, 1);
  //Schrijf de batterij icoontjes naar het LCD
  lcd.write(1);
  lcd.write(2);
  lcd.write(3);
  lcd.write(4);
  lcd.write(5);
  lcd.write(6);
  lcd.write(7);
}

```

# Answer
> 1 votes
You could use a driver for stepper motors, so you can control the motors using PWM. You call the PWM from Arduino using analogWrite(). After a call to analogWrite(), the pin will generate a steady square wave of the specified duty cycle until the next call to analogWrite() (Read this link from the Arduino page). This will help you in your project, and maybe find the solution to your problems when reading the sensor at the same time. An advantage of using PWM is that you can also made smoother movement for your robot when it is crossing or finding its way.

I also recommend using two sensors (I suppose you're using IR), so if you want to track the black surface and there is a turn, one of the sensors will be detecting the line, and the other one wont. That way you can assume which way should the robot turn, making it more efficient.

# Answer
> 0 votes
> is there a way to program the line tracker without having it interfere on my stepper motors?

you are simply generating a pwm signal to drive your steppers. So make that generation in the background, through a timer isr for example.

Thus your main loop() will just be doing the low priority stuff.

---
Tags: arduino-uno
---


# Question
Title: Cycling LED's for specific time period with millis()
My goal in pseudo code is :

```
only LED-6 HIGH for 6 seconds, then only LED-7 HIGH for 2 seconds, then only LED-8 HIGH for 4 seconds, then restart

```

This is very easy with delay(), but I struggle with millis(). Here is my code. Only led 7 and 8 blinks.

```
unsigned long currentTime;
unsigned long previousTime1 = 0;
unsigned long previousTime2 = 0;
unsigned long previousTime3 = 0;
unsigned long interval1 = 6000;
unsigned long interval2 = 2000;
unsigned long interval3 = 4000;

void setup() {

  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);

}

void loop() {

  currentTime = millis();

  if (currentTime - previousTime1 >= interval1){
    previousTime1 = currentTime;
    digitalWrite(6, HIGH);
    digitalWrite(7, LOW);
    digitalWrite(8, LOW);
  }

  if (currentTime - previousTime2 >= interval2){
    previousTime2 = currentTime;
    digitalWrite(6, LOW);
    digitalWrite(7, HIGH);
    digitalWrite(8, LOW);
  }

   if (currentTime - previousTime3 >= interval3){
    previousTime3 = currentTime;
    digitalWrite(6, LOW);
    digitalWrite(7, LOW);
    digitalWrite(8, HIGH);
  }
}

```

# Answer
> 1 votes
A way to make this work is to use only one `previousTime` variable, rather than three of them.

When the program as shown above starts out, `millis()` is in fact close to 0, so none of the three LEDs should light up in the first 2 seconds. At the 2 second mark, LED 7 comes on. `previousTime2` gets set to current time, so the second `if` is not going to be satisfied for 2 more seconds. At that point, LED 7 and 8 are in a race to see which one turns on second; whichever turns on first at the 4-second mark gets turned off within milliseconds, because when any LED turns on, the code turns off the other two LEDs. Whenever the condition for LED 6 is met, so is the condition for at least one of 7 or 8; so 6 can't stay on more than 2 seconds at most, and even then is in a race with 7 and 8 to come in third.

With a single `previousTime` variable, code like the following might work.

```
current = (millis() - previousTime)/1000;
if (current < 6) {
  digitalWrite(6, HIGH); // turn on 6
} else {
  digitalWrite(6, LOW);  // turn off 6
}
if (current >= 6 && current < 8) {
  digitalWrite(7, HIGH); // turn on 7
} else {
  digitalWrite(7, LOW);  // turn off 7
}
if (current >= 8) {
  digitalWrite(8, HIGH); // turn on 8
} else {
  digitalWrite(8, LOW);  // turn off 8
}
if (current >= 12) {
  previousTime = millis();
}

```

Note, the following code has the same effect.

```
current = (millis() - previousTime)/1000;
digitalWrite(6, current < 6);                 // turn 6 on or off
digitalWrite(7, current >= 6 && current < 8); // turn 7 on or off
digitalWrite(8, current >= 8);                // turn 8 on or off
if (current >= 12) {
  previousTime = millis();
}

```

---
Tags: millis
---


# Question
Title: Adding to the counter only ONCE while R2 =<200
I am very new to Arduino and I have this little bit of code:

```
if (R2 <= 200){
  counter=counter+1;
  Serial.print("counter: ");
  Serial.println(counter);
}

```

I want it to count every time R2 is less than or equal to 200, but I only want it to count once. Right now it adds to the counter 3-2 times while R2 is less than 200. I'd like it to only count once while in that range before R2 becomes greater than 200.

Any suggestions or links to helpful information would be very appreciated. Thank you!

# Answer
> 1 votes
You can set a flag to indicate that R2 is or has been above 200 since it last was low, much as follows.

```
// before loop() ...
byte Rhi = true;  // at outset, say that R2 has been high
...

// in loop() ...
  if (R2 > 200)          // Has R2 gone high?
    Rhi = true;
  if (Rhi && R2 <= 200){ // Has R2 gone low from high?
    Rhi = false;
    ++counter;
    Serial.print("counter: ");
    Serial.println(counter);
  }
  ...

```

---
Tags: arduino-uno
---


title: WiFi.status() hangs / resets board

text:
# Question
Title: WiFi.status() hangs / resets board
Using one of the RobotDyn boards with onboard WiFi and a Generic ESP8266 module.

I can load the sketch, but when `WiFi.status()` is called to see if WiFi enabled, the sketch hangs, rebooting the board after ten seconds are so.

```
void setup() {
  Serial.begin( 115200 );
  Serial.println( "begin - wifi status: " );
  // program hangs here - - - - - - -
  int status = WiFi.status();
  Serial.println( status );
}

```

# Answer
I think it might be a problem with the code you are using, prior to version 2.2.0 of the "ESP Core" the first block of code worked, since only the second version works.

It seems that you can get around it by rather than doing this:

```
 WiFi.begin(ssid, password); // connect to the network
 while (WiFi.status() != WL_CONNECTED)
 {
     delay(500);
 }

```

You should do this:

```
if (WiFi.status() != WL_CONNECTED)
{
     WiFi.begin(ssid, password); // connect to the network
     delay (500);
}

```

Does that look it might be a likely cause?

Sources
> 1 votes

# Answer
Think I found the cause!

I previously had

```
#include <WiFi.h>

```

but now using

```
#include <ESP2866WiFi.h>

```

This seems to work

I was unaware of the two library sets. Since I use both `Arduino MiniPro` and versions of `NodeMCU`, am now going through the libraries and determining what breaks.

IMHO, in regard to libraries, `NodeMCU` Lua libraries are far, far better than `Arduino's` C++ libraries.
> 1 votes

---
Tags: esp8266, wifi
---


title: Expected ')' before ';' token Error

text:
# Question
Title: Expected ')' before ';' token Error
Me and my friend have a project to do and we can't seem to figure out why the code we used for our Arduino Nano Board isn't compiling giving us the `Expected ')' before ';' token` Error

Here is the code:

```
// connect motor controller pins to Arduino digital pins
// motor one
int enA = 10;
int in1 = 9;
int in2 = 8;
// motor two
int enB = 5;
int in3 = 7;
int in4 = 6;

void setup()
{
  // set all the motor control pins to outputs
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
}
void demoOne()
{
  // this function will run the motors in both directions at a fixed speed
  // turn on motor A
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  // set speed to 200 out of possible range 0~255
  analogWrite(enA, 200);
  // turn on motor B
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
  // set speed to 200 out of possible range 0~255
  analogWrite(enB, 200);
  delay(2000);
  // now change motor directions
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  delay(2000);
  // now turn off motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
}
void demoTwo()
{
  // this function will run the motors across the range of possible speeds
  // note that maximum speed is determined by the motor itself and the operating voltage
  // the PWM values sent by analogWrite() are fractions of the maximum speed possible
  // by your hardware
  // turn on motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  // accelerate from zero to maximum speed
  for (int i = 0; i ; 256; i++)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  }
  // decelerate from maximum speed to zero
  for (int i = 255; i (&gt);= 0; --i)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  }
  // now turn off motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
}
void loop()
{
  demoOne();
  delay(1000);
  demoTwo();
  delay(1000);
}

```

We could really use some help.

# Answer
Well, for example `for` doesn't have four parts but three

```
for (int i = 0; i ; 256; i++) // => for (int i = 0; i < 256; ++i)

```

Next one doesn't look much better:

```
for (int i = 255; i (&gt);= 0; --i) // =>  for (int i = 255; i >= 0; --i)

```

There might be more, but these are really obvious. Like you copied it from some website with some characters translated into the html entities.
> 4 votes

---
Tags: serial, programming, motor, arduino-nano
---


title: Serial printf implementation

text:
# Question
Title: Serial printf implementation
Based on this approach I wanted to implement a function for formatted printing data to the serial monitor. I tried the code below:

```
int PIN = 12;

void _printf(char *fmt, ...) {
  va_list va;
  va_start(va, fmt);
  char buf[vsnprintf(NULL, 0, fmt, va) + 1];
  sprintf(buf, fmt, va);
  Serial.println(buf);
  va_end(va);
}

void setup() {
  Serial.begin(9600);
  Serial.println("serial monitor has been set up");
  char buf0[vsnprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
  sprintf(buf0, "pin %i configured to output", PIN);
  Serial.println(buf0);
  _printf("pin %i configured to output", PIN);
  char buf1[vsnprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
  sprintf(buf1, "pin %i configured to output", PIN);
  Serial.println(buf1);
  _printf("pin %i configured to output", PIN);
  pinMode(PIN, OUTPUT);
  char buf2[vsnprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
  sprintf(buf2, "pin %i configured to output", PIN);
  Serial.println(buf2);
  _printf("pin %i configured to output", PIN);
  char buf3[vsnprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
  sprintf(buf3, "pin %i configured to output", PIN);
  Serial.println(buf3);
  _printf("pin %i configured to output", PIN);
}

void loop() { }

```

But it gives me some weird output:

```
serial monitor has been set up
pin 12 configured to output
pin 2263 configured to output
pin 12 configured to output
pin 2234 configured to output
pin 12 configured to output
pin 2205 configured to output
pin 12 configured to output
pin 2176 configured to output

```

What do `2263` and `2269` mean? Why does it happen only inside the function? What is my mistake and how can I fix it?

# Answer
The problem with your code is that you are mixing the "normal" and "variadic" forms of the printf functions.

Any printf function starting with V takes a variadic argument list pointer as its last variable. Any printf function which doesn't start with V takes a variadic list of individual variables.

When calculating your buffer size from a list of variables in your main loop you are incorrectly using `vsnprintf` \- you should be using `snprintf` since you aren't passing it a `va_list`, but individual variables. In your `_printf` function you are correctly using `vsnprintf` to calculate the length of the buffer, but then incorrectly using `sprintf` with a `va_list` instead of individual variables.

So your two forms should actually be re-written as:

```
// Inline version
char buf0[snprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
sprintf(buf0, "pin %i configured to output", PIN);
Serial.println(buf0);

```

and:

```
void _printf(char *fmt, ...) {
  va_list va;
  va_start(va, fmt);
  char buf[vsnprintf(NULL, 0, fmt, va) + 1];
  vsprintf(buf, fmt, va);
  Serial.println(buf);
  va_end(va);
}

```

Remember: if you have a `va_list` then it goes with a `v*printf` function. If you have individual variables they go with a `*printf` function.
> 2 votes

---
Tags: serial, printf
---


title: Help combining code

text:
# Question
Title: Help combining code
Can someone please help me fix my code?

Basically, a user inputs values that determine how many beeps will play from a breadboard-compatible speaker, and right after the beeps are played, a motor (connected to the breadboard) is supposed to turn.

The beep-code is mine, and I got the motor code from the Arduino website. Anyway, SEPARATELY the codes work - the beeps play from the speaker, the motor turns fine. However, the codes don't work when I combine them (beeps play, but motor does not run after beeps are played), and I have no idea how to fix it. Any help is appreciated. Thanks so much.

```
int pin = 3;
#include <Stepper.h>

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

void loop() {
  int bpmeasure, measurespg, bpminute;
  Serial.println("Enter number of beats per measure:");
  while (Serial.available() == 0) {};
  bpmeasure = Serial.parseInt();
  Serial.println(bpmeasure);
  Serial.println("Enter number of measures on page:");
  while (Serial.available() == 0) {};
  measurespg = Serial.parseInt();
  Serial.println(measurespg);
  Serial.println("Enter tempo:");
  while (Serial.available() == 0) {};
  bpminute = Serial.parseInt();
  Serial.println(bpminute);
  float tppg = (bpmeasure * measurespg * 60000.0) / bpminute;
  // time it takes to play a page, in milliseconds
  float tpbeat = tppg / (bpmeasure * measurespg);
  // time between each individual note, in milliseconds
  float t = 0.0;
  for (float t = 0.0; t <= tppg ; t += tpbeat) {
    tone (pin, 30, 50);
    delay (tpbeat+50);
  }
  // speaker is supposed to beep every 'tpbeat' amount of milliseconds,
  // until it reaches 'tppg' milliseconds and then speaker should stop beeping
  const int stepsPerRevolution = 900;
  Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
  int stepCount = 0;
  // number of steps the motor has taken
  if (stepCount = 0) {
    // read the sensor value:
    int sensorReading = analogRead(A0);
    // map it to a range from 0 to 100:
    int motorSpeed = map(sensorReading, 0, 1023, 0, 100);
    // set the motor speed:
    if (motorSpeed > 0) {
      myStepper.setSpeed(motorSpeed);
      // step 1/100 of a revolution:
      myStepper.step(stepsPerRevolution / 100);
    }
  }
}

```

# Answer
The first step with combining any programs together is to forget about combining programs together. Instead you need to do something completely different.

Analyse the existing programs individually. Work out and learn exactly how they work and how they do what they do.

Then think about your program. What do you actually want it to do, and how does that relate to the things the other programs did.

Then, finally, using what you learned from analysing the other programs, you write your own new program that does what you want it to do.

Yes, there may be a certain amount of copy-and-paste from the old programs to the new, but until you have taken the time to learn how the old programs work you won't have a clue which parts of them you may want to copy-and-paste, and which you may want to use as inspiration for writing new portions of code.
> 3 votes

---
Tags: motor, code-review
---


# Question
Title: ESP8266 doesn't respond to Serial.println("AT")
If I don't declare `Serial.begin(115200)`, I can send `AT` commands over serial monitor and it replies me.

But when I declare `Serial.begin(115200)` and send `AT` commands inside program or serial monitor there is nothing happens.

Did I miss something?

# Answer
> 2 votes
You have connected the tx of the Arduino to the tx of the ESP8266 and the rx of the Arduino to the rx of the ESP8266.

What is happening when you type AT in the Serial Monitor is that you are communicating directly with the ESP8266, and not with the Arduino.

You need to connect the rx of the Arduino to the tx of the ESP8266 and the tx of the Arduino to the rx of the ESP8266.

This has asked and answered a number of times, such as:

Arduino Uno and ESP8266 serial monitor issue

Arduino & ESP8266

Arduino Nano v3.0 with ESP8266

ESP 8266 does not respond at all

Your ESP8266 definitely uses a baud rate of 115200 (as confirmed by your first screen shot), so you don't need to change that when experimenting.

# Answer
> 0 votes
Thank you for the answer @Holmez, third link was very helpful. I was just change the code and the RX, TX pins like below and it works perfect now. I can send commands to the ESP both in program and over the serial monitor.

```
#include <SoftwareSerial.h>

SoftwareSerial wifi(10, 11);

void setup() {
  Serial.begin(115200);
  wifi.begin(115200);
  Serial.println("Test");
  wifi.println("AT+CIFSR");
}

void loop() {
  if (Serial.available()) {
    wifi.write(Serial.read());
  }
  if (wifi.available()) {
    Serial.write(wifi.read());
  }
}

```

---
Tags: arduino-uno, esp8266
---


# Question
Title: Arduino Uno: Sensor shield powering multiple servos
I posted this on the electrical side of stack exchange and they said it was off topic, so I think it will be on topic here and they confused me even more. So if you guys could clear up my confusion, that would help.I know there are sources for this, but I am still lost. Anyways, here is the run down. I want to control multiple servos (12 of them) using a sensor shield. I need to know what kind of power supply I need. Here is the servo's I am using:

https://www.amazon.com/gp/product/B01NA80LUR/ref=oh\_aui\_detailpage\_o02\_s00?ie=UTF8&psc=1

Here is the sensor shield I am using:

https://www.amazon.com/gp/product/B01ACKVPTW/ref=oh\_aui\_detailpage\_o01\_s00?ie=UTF8&psc=1

The servos run at 3-7.2V and 750ma-1000ma full load or another person said they ran only 100-150ma. Also, another question is do I plug that power supply, when I get the right one according to what you say, into the dc jack or the external power on the sensor shield board?

Thank you for your time.

# Answer
> 0 votes
Arduino.cc forum topic 229646, “Arduino Sensor Shield v5 (APC220) manual”, is a thread about lack of documentation for that shield. However, post #10 in that thread states that pulling off the SEL jumper allows you to use an external power supply to power the devices you attach to the shield. Also see *Sensor Shield (Version 5X) Separate 5V for Servos* at yourduino.com.

The Robotics Stackexchange question *Wiring & driving TowerPro SG90 servos* agrees with the 750–1000 mA current draw of SG90 servos. You could go with a 5 or 6 V power supply, with say 12 A rating if you expect to drive 12 servos at the same time. However, as a 12 A supply might be expensive, you probably should attach two or three servos to the shield and measure the current draw. If, for example, your application rarely draws over half an amp per servo, you might scale back to a 10 A or 8 A supply.

Note that an Arduino Uno or Nano (in general, any based on ATmega328-like MCUs) has six pins that support hardware PWM, so you may need to use a Mega instead, or two Uno or Nano Arduinos. (Software-generated PWM signals are another possibility but I doubt it would work well enough if your app is at all complicated.)

---

*Edit 1:* If the system is battery operated, you probably should use a 2S LiPo RC battery, that is, a battery with the voltage of two lithium polymer cells in series (so, 7.4 volts) and whatever number of cells you wish to pay for in parallel, as often used in radio controlled devices.

Some LiPo batteries support 25C discharge rates, ie, can discharge at 25 times their one-hour-discharge rating. Thus, a 500 mAh battery might work fine – since 25 times .5 A is 12.5 A – if you only need to run your system for up to 2.4 minutes between battery charges. Or, for example, a $13.49 Turnigy 1000mAh 2S 20C Lipo Pack HobbyKing RC Battery would work ok, even though only rated for 20C. It could power a 12 A draw for 1/12 hour, or 5 minutes.

---

For the SEL jumper, look in the lower left corner of one of the pictures from your amazon.com link, as below. With the jumper (the short-metal-strap-and-black-plastic-shell assembly, next to the letters SEL) removed, connect battery+ and battery- to the screw-down terminals at bottom left in the photo. Battery+ goes to Vcc, battery- to Gnd.

---

Regarding a second Arduino, you could split the processing across two of them so that each one only needs to know the current time; or could communicate between them by an SPI, I2C, or RS232 interface; or could move up to a Mega2560 Arduino, which has a lot more PWM channels.

*Edit 2:* If battery weight is an issue, you may be able to use lower-capacity (hence lighter-weight) batteries if your software only moves a few of the servos at the same time. For example, if you move three or four at a time, and if most of the servos are idle most of the time, you might be able to use a light-weight cellphone battery.

Addicore.com has some useful current measurements for the SG90:

```
Voltage                        4.0V to 7.2V, 4.6V - 5.2V nominal
Running current with 5V supply (no mechanical load)    220 ±50mA
Stall current with 5V supply (horn locked)             650 ±80mA
Idle current with 5V supply                              6 ±10mA
Weight                                                0.32oz (9g)

```

However, you probably need to make current measurements on your own to see how big the battery needs to be.

# Answer
> 0 votes
two things make servos fairly easy to control:

1. they take a slow pwm input; generating pwm is fairly easy on a mcu;
2. they are generally not that sensitive to the duration of the off state: I have tried from 5ms to 40ms (the longest) and they are fine with that.

so if you combine the two attributes together, it is easy to control multiple servos with from one timer interrupts.

I wrote a few pages on this recently: 1. driving multiple servos on AVR Timer2: https://dannyelectronics.wordpress.com/2017/02/08/driving-multiple-servos-with-avr-timer2/

2. driving multiple servos on PIC: using TIMER0 (https://dannyelectronics.wordpress.com/2017/02/08/driving-multiple-servos-with-pic-timer0/) or TIMER1 (https://dannyelectronics.wordpress.com/2017/02/07/driving-multiple-servos-with-pic-timer1/).

The following is a combination of the two: driving 8 servos independently on PORTB with TIMER1 and another 8 servos independently on PORTD with TIMER2.

the user code is quite simple:

```
//set up servo controller 1
srvo1_init();                           //reset the servo module
srvo1_setpr(1, 1000);                   //for 1ms
srvo1_setpr(2, 1200);                   //for 1.2ms
srvo1_setpr(3, 1400);                   //for 1.4ms
srvo1_setpr(4, 1500);                   //for 1.5ms
srvo1_setpr(5, 1800);                   //for 1.8ms
srvo1_setpr(6, 2000);                   //for 2ms
srvo1_setpr(7, 2500);                   //for 2.5ms
srvo1_setpr(8, 4000);                   //for 4ms

//set up servo controller 2
srvo2_init();                           //reset the servo module
srvo2_setpr(1, 1000);                   //for 1ms
srvo2_setpr(2, 1100);                   //for 1.1ms
srvo2_setpr(3, 1200);                   //for 1.2ms
srvo2_setpr(4, 1300);                   //for 1.3ms
srvo2_setpr(5, 1400);                   //for 1.4ms
srvo2_setpr(6, 1500);                   //for 1.5ms
srvo2_setpr(7, 2000);                   //for 2ms
srvo2_setpr(8, 4000);                   //for 4ms

```

Once it is set-up, you can just leave it alone and no addition attention is required. You can change the duration of course, or disable / re-enable output on a given channel.

Total CPU drain is about 150K ticks in a second for 16 channel controller.

works on Arduino as well.

edit: if you port the code to TIMER0 (easily done), you can control 32 servos independently.

and if you combine this code with making timers out of the output compare functionality, you can shrink them all on one timer.

---
Tags: arduino-uno, servo
---


title: ESP8266 & Initial State

text:
# Question
Title: ESP8266 & Initial State
Has anyone been successful in connecting an ESP8266 to the Initial State IoT platform?

On the platform there is only one example with Cactus ESP. I tried it but it did not work because I have a NodeMCU.

Can you please share your Arduino code?

# Answer
If you use the Arduino IDE Board Manager to install the support for ESP boards an ESP8266 can be programmed in EXACTLY the same way as you program an Arduino.

This mean you will now be able to follow the Cactus Micro sample up to the point where you upload CMTempTest.ino.

The problem with the HubTest.ino code is that relies on having a serial link between the Cactus board's main processor and its ESP8266 network slave processor. You don't have that so all the AT commands are not going to work.

However you do have a number of examples that come with the ESP addition to the IDE and in there will be a network client example. You need to look at how that code forms a connection and make HubTest.ino work in that way. I can't tell you exactly what to do (I don't know) but any lines that are AT related need to be replaced by "proper" networking code.
> 1 votes

---
Tags: esp8266
---


# Question
Title: Powering Arduino through 12V USB communication unstable
When powering Arduino through Japan Jack at 12V USB communication becomes unstable and frequently interrupts/disconnects. Using Arduino Uno R3 and Linux on the connected computer.

Does anyone have any insight why this might be happening?

# Answer
12V is a little on the high end for what the arduino can handle by itself. If I were you I would use a DC step down Buck Converter module to hold the voltage at somewhere around 6v.

http://www.ebay.com/itm/like/400673913185?lpid=82&chn=ps

They're super cheap and pretty easy to use. Simply solder the + and - leads from your 12v power supply to the +in and -in on the buck converter. Then the + out and -out to the + and - for your arduino. Turn the potentiometer until you get somewhere around 6V.

Edit:

Actually I was just reading online, and some people have trouble communicating with the arduino through USB while an external power source is connected. Internet says this problem is related to sharing voltages.

https://forum.arduino.cc/index.php?topic=194598.0
> 1 votes

---
Tags: usb, communication, battery
---


# Question
Title: I need a simple, low power, low cost wireless switch to transmit to Arduino
I'm looking for a very simple wireless, low-power, low-cost switch that can transmit a signal to an Arduino. Ideally, each transmitter would have a signature. For instance, let's say I had 4 different transmitters that are attached to a sensor. When the sensor is tripped, I want to wirelessly send a signal to the Arduino. I've looked at these 433 MHz modules, but it seems like they would also need a microcontroller to send the data, while that's a possible solution, I'm wondering if there is a even smaller, simpler solution.

# Answer
> 1 votes
There is no such thing as a transmitter that can attach direct to a sensor, since no two sensors in the world work the same way. You need something intelligent between the sensor (to read the sensor value) and the transmitter (to tell it what to transmit).

There are "all in one" modules, like the ESP8266, which have an MCU and WiFi combined in one chip which are closer to what you want, but it is still down to you to program those modules to work how you need them to work for your sensors.

# Answer
> 0 votes
You could use an infrared led and an infrared sensor combined with a simple circuit to send a series of flashes that only your arduino can read. The only downside to this is that infrared can only be used indoors and they don't work if you don't have a direct line of sight.

---
Tags: arduino-nano, wireless, switch
---


# Question
Title: Burning the Arduino bootloader without an extra Arduino board
Is there any way to burn the Arduino bootloader on a standalone Atmega328 (internal clock 8MHz) from the Arduino official website without using an extra Arduino board to burn the bootloader?

I mean, is it possible to burn the bootloader on the Arduino and then remove the ATmega chip from the Arduino board and use it in a breadboard?

Thanks.

# Answer
If you don't want to go the route of a dedicated programmer, you could try ArduinoISP where you can program an Arduino board (with a Mega on it) to be a programmer for another AVR device (e.g. another Mega). The instructions can be found at https://www.arduino.cc/en/Tutorial/ArduinoISP and allows you to do something like this:
> 3 votes

# Answer
Yes, use an ISP programmer. I personally use Atmel ICE, Arduinos as ISP and USBasp.

AVRISP is another popular option:

This tutorial might be useful: Sparkfun.
> 0 votes

---
Tags: bootloader
---


# Question
Title: Arduino board as USB/serial for a Nano with broken USB
I broke the USB connector on an Arduino Nano and I am trying to use my Uno board as a USB/serial adapter to be able to upload sketches. The broken Nano came with a customized bootloader (*avrdude -c arduino* compatible), which I do not have a copy of. The content in the HEX files I have is encrypted, it has to go through the bootloader for the plain code to be flashed. This rules out ISP.

I came up with this:

Please note that the ATMega on the Uno board is **removed**. As I am proxying the Nano through the Uno board, I am wiring RX to RX and TX to TX.

The problem I face is that it seems the Nano board is not receiving data from the PC. Everything else works:

* pressing the reset button on either board resets the Nano
* TX from the Nano goes back to the PC (the current sketch on the Nano prints some stuff on boot), TX leds blink accordingly on Nano and Uno boards
* RX led on the Uno board blinks when PC sends something, *but RX led on the Nano board does not blink in that case*
* connecting the RX/TX Nano pins to a USB/serial cable lets me send and receive data to/from the sketch

I tried with another, non-broken, Nano (standard bootloader) and I have the same issue, so I think the broken Nano is fine. If I upload a sketch that continuously writes to the serial port, the PC receives it. If I upload an "echo" sketch, I do not get anything back (the "echo" works well over direct USB connection).

I am a software guy, my apologies if I am doing something obviously wrong. I read several pages on the topic, I couldn't spot a fix. The boards are not official Arduino products, but I am not sure this is relevant. I wonder if part of the answer is related to the fact that the USB/serial conversion is handled by a Mega16U2 chip rather than something like a CH340, now useless on the broken Nano.

Some links that I checked:

# Answer
As explained in comments by Chris Stratton, both the Mega16U2 on the Uno and the USB/serial chip on the Nano are competing for the signal level. Removing the resistors on the RX/TX lines between the USB/serial chip and the ATMega on the Nano board will prevent it from interfering with the signals exchanged with the Uno.
> 1 votes

---
Tags: usb, serial
---


# Question
Title: Start/Stop/Reset the melody using buttons
I have 2 buttons. Button 1 will start/stop the melody while the button 2 will reset the melody. My melody is "Happy Birthday".

How am I going to use the buttons to start/stop/reset the melody?

Here's the code:

```
#include "pitches.h"

int melody[] = {
    NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, NOTE_C4, NOTE_B3,
    NOTE_G3,NOTE_G3, NOTE_A3,NOTE_G3, NOTE_D4, NOTE_C4,
    NOTE_G3, NOTE_G3, NOTE_G4,NOTE_E4,NOTE_C4, NOTE_B3, NOTE_A3,
    NOTE_F4, NOTE_F4, NOTE_E4, NOTE_C4, NOTE_D4, NOTE_C4
};

int noteDurations[] = {
    8,8,4,4,4,2,8,8,4,4,4,2,8,8,4,4,4,4,3,8,8,4,4,4,2
};

boolean needtoPlay;

void setup() {
    pinMode(4, OUTPUT);
    pinMode(2, INPUT); //START/STOP
    pinMode(3, INPUT); //PAUSE
}

void loop() {
    for (int thisNote = 0; thisNote < 26; thisNote++) {
        int noteDuration = 1000 / noteDurations[thisNote];
        tone(4, melody[thisNote], noteDuration);
        int pauseBetweenNotes = noteDuration * 1.60;
        delay(pauseBetweenNotes);
        noTone(4);

        if (needToPlay == true) {
        }
    }
}

```

# Answer
Modify your code so notes will play using timer interrupts instead of delay(). Once your program is inside delay(), no button will be responded. Done that, you just have to read buttons either by polling them with digitalRead or using interrupts.
> 1 votes

# Answer
Easiest way would be to add this to the end of the for loop (inside the loop). Assuming buttons are pulled up.

```
//setting pause with pause button
if (digitalRead(pauseButtom) == LOW) {
    //it will not play while in this loop
    while (true) {
      //if the button is pressed again, exit the loop
      if (digitalRead(pauseButtom) == LOW) {
        break;
      }
      delay(10);
    }
}

```

For the reset, just break; it will exit the for loop and start again.

Alternately, instead of using a for loop, use a counter and increment / reset it. You will need to store most variables globally.

```
if(!paused) {
  //play note
  if (counter < numNotes) {
    counter++;
  } else {
    counter = 0;
  }
}

if (digitalRead(pauseButtom) == LOW) {
  pause = !pause;
}

if (digitalRead(resetButtom) == LOW) {
  counter = 0;
}

```

You could move those last 2 conditionals to interrupts.
> 1 votes

---
Tags: arduino-uno, code-review, buzzer
---


# Question
Title: Checking for multiple values in IF separated by commata
My code is:

```
if ((minute == 31) && (hour == 4, 6, 9, 11))
{
  digitalWrite(8, HIGH);
}

```

I want to turn on the LEDs when it is exactly

* 04:31,
* 06:31,
* 09:31,
* 11:31

However, the code above doesn't work.
Might be the multiple values the reason for this?

# Answer
Yes, the list of values `4, 6, 9, 11` does not mean what you think it does.

```
if ((minute == 31) &&  ((hour == 4) || (hour == 6) || (hour == 9) || (hour == 11))) {
    digitalWrite(8, HIGH);
}

```
> 1 votes

# Answer
Optionally, you could store the values in an array and go across all of them with some code like this:

```
int hours = [4,6,9,11];

function isInArray(inputValue, array) {
    boolean isIn = false;

    for ( int i = 0; I < array.length; i++) {
        // "isIn |= statement" is shorthand for "isIn = (isIn || statement)"
        isIn |= (array[I] == inputValue);
    }

    return isIn;
}

if (isInArray(variable, hours)) {
    //do whatever
}

//might be able to do
if (isInArray(variable, [4,6,9,11])) {
    //do whatever
}

```
> -1 votes

---
Tags: c++, variables
---


title: ESP8266 cannot read DHT22

text:
# Question
Title: ESP8266 cannot read DHT22
I am trying to build a WiFi humidity and temperature sensor. My board is a nodeMCU using the ESP8266 connected via USB. The board is working fine with various WiFi examples and various serial examples. Hence I guest my environment is OK.

Now I am trying to connect a DHT22 to read temperature and humidity. To reduce the error sources I boiled down my code to the standard DHT example:

```
// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain
#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT22   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println("DHTxx test!");
  dht.begin();
}

void loop() {
  delay(2000);

  float h = dht.readHumidity();
  float t = dht.readTemperature();
  float f = dht.readTemperature(true);
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.println(" *C ");
}

```

Nevertheless I always get the message "Failed to read from DHT sensor!".

Regarding the hardware I tried connecting the sensor with or without the 10k resistor, tried different DHTs and different pins. To rule out the DHTs I connected them with an Arduino Nano where these are working fine (both with and without resistor and using the same code). The only difference I see is that the Arduino is using 5V while the ESP8266 is using 3.3V - which is nonetheless inside the rating of the DHT.

Any ideas?

# Answer
> 5 votes
I found, that the pin mapping printed at the board of the nodeMCU does NOT match the pin mapping in the library/software.

Check out this issue/solution. It states the correct pin mapping (e.g. pin 2 is "D4" at the board) and provides also an according workaround. My DHT22s are working now... :-)

# Answer
> 0 votes
I had been racking my brain for over 16 hours trying to figure out why this library would not work. I tested the DHT on an Arduino and it worked fine but whenever I tried on the nodeMCU it failed to read or gave spurious data. That is untill I saw the above answer that is not mentioned anywhere. The pins for the nodeMCU are not the same as the Arduino. (I thought that by defining the pin it would be using the pin stated) This is false as the library is mapped the Arduino pins so this is something to look out for, for any nodeMCU/ESP8266 beginners.

---
Tags: arduino-nano, esp8266, temperature-sensor
---


# Question
Title: Can I monitor data of variables while simulating Arduino on Proteus?
I simulate Arduino UNO on proteus 8 Pro. I use Arduino software for writing a program.

Is it possible to trace or know the data that are stored in valuables while running the code on Proteus?

I would like to know how the code is running step by step so that I can find logical errors.

Thank you,

# Answer
> 0 votes
It is possible. By using several tools on "Virtual Instruments Mode" such as SPI-Debugger, I2C-Debugger, Virtual Terminal, or Logic Analyser.

> I would like to know how the code is running step by step so that I can find logical errors.

For example, you can use Virtual Terminal and print the value of variables you want to examine

---
Tags: simulator
---


title: Square LED vs Round LED

text:
# Question
Title: Square LED vs Round LED
I'm trying to choose between square or round LEDs. I would like to select an LED that will "project" light and I cannot find any information comparing the two types.

Which style of LED will project light better?

Projection, for the purposes of this question, means casting light "in-line" with the LED. For example, an LED right out of the box with straight leads plugged into a breadboard on a flat table will stand vertically. In this case, I would like to project as much light onto the ceiling as possible. I hope this makes sense.

If it matters, I'd like to use water clear blue LEDs.

# Answer
> 2 votes
Many of the square or rectangular LEDs with leads – that is, not surface mount devices (SMD) – that I've seen are intended for use as panel indicator lights, so are not very bright. On the other hand, among SMD devices square, rectangular, and round lights run the whole gamut of brightness. Of course many white LEDs, square or round, are extremely bright because of being intended for illumination.

For projecting a beam against a ceiling, adding optics to the LED may be the best approach. For example, buy some 99¢ flashlights like “Waterproof 3500LM Pocket LED Flashlight Zoomable LED Torch Mini Penlight Light” on ebay, and either add a blue filter in front of the lens or replace the LED with an ultrabright blue LED, using the zoomed-out flashlight lens to concentrate the light. Also, search for 10° or 15° “PMMA LED lens” on ebay, Amazon, aliexpress, etc.

Note, for determining if any given LED will project a tight bright beam, look at the angles of its beam pattern.  This diagram (from Led Buying tips at sunriseled.us) contrasts the intensity of a 30°-beam LED with that of a 70°-beam LED. The diagram at left below (from dimmable-gu10.com) is typical of intensity-vs-angle diagrams, which usually are shown on a polar plot like that, with a narrower oval corresponding to a tighter beam. The diagram at right below shows the same information, in a perhaps more easily comprehended form.

---
Tags: led
---


title: Read frequency to voltage with Arduino

text:
# Question
Title: Read frequency to voltage with Arduino
How to read frequency into voltage with Arduino with an external source of frequency of 0-1Khz max?

# Answer
> 2 votes
In the past I used the LM2917 for this purpose:

http://www.ti.com/lit/ds/symlink/lm2907-n.pdf

That IC is a frequency to voltage converter, so it perfectly suits your need. According to some quick calculations I made it can go to some tens of kHz, so if your signal is up to 1kHz it should be fine.

Now, this is the answer to your question. But... You can easily read the frequency directly with the arduino... If your purpose was to read the frequency, I suggest you to read something about the X-Y problem

---
Tags: pwm, frequency
---


# Question
Title: Why does the Arduino Uno WiFi network connection drop when requesting a page?
I see frequent errors where the network connection to my Arduino Uno WiFi drops when I am requesting a web page. I wrote a simple REST server, and some of the pages will load as expected, but others will fail after loading half of the the text, and I notice that the network connection drops in the middle of these events. Why is the network connection dropping like this?

# Answer
I saw this error when I was running low on RAM. The Arduino Uno WiFi appears to drop the network connection in low memory situations. One fix that made a significant difference for my program was to wrap all of the string literals in the F() macro. This moves the strings from ram to flash storage, and in my case quickly freed 500 bytes of SRAM (25% of the available RAM on this board). For example, replace:

```
client.println("HTTP/1.1 200 OK");

```

with

```
client.println(F("HTTP/1.1 200 OK"));

```

Some other memory optimization may also be necessary. Another possible cause of these symptoms would be low voltage, possibly from trying to draw too much power from the board to power external devices, but in my case there were no external connections, and I confirmed it was a low-memory issue.
> 1 votes

---
Tags: wifi
---


# Question
Title: Can I connect an Arduino wifi module directly to my android phone?
I would like to use my arduino even where there's no wifi router. I've only found people saying that it needs to connect to a router, but isn't the phone like a router when it's in tethering mode? Do I still need a mobile internet connection or can I do it directly?

# Answer
A phone running in wifi tethering (mobile hotspot) mode is no different to a wifi access point or router. So yes, you can use that.

Chances are though that you will need a mobile internet connection in order to activate mobile hotspot mode in the first place.
> 1 votes

# Answer
If you are using the Arduino UNO WiFi Board (http://www.arduino.org/products/boards/arduino-uno-wifi) with the built in ESP8266 chip then your phone can connect directly to the Arduino's network and you can interact with it that way.

With the default firmware, this board can simultaneously connect to a local WiFi network, and create its on access point. This is very handy because it means that you can connect and access its hosted web pages even without a WiFi router with no extra setup steps, or special configuration.
> 0 votes

---
Tags: wifi
---


# Question
Title: 32x32 RGB-LED Matrix displaying Arabic Font with Font Forge more easily
At the moment I am using a separate function to display byte arrays like these:

```
const PROGMEM unsigned char arab4[] = {
  0x00, 0x00, 0x00, 0x00,
  0xf0, 0xff, 0xff, 0x01,
  0xf8, 0xff, 0xff, 0x01,
  0xf8, 0xff, 0xff, 0x00,
  0x04, 0xf8, 0x0f, 0x00,
  0x00, 0x7c, 0x00, 0x00,
  0x00, 0x0e, 0x00, 0x00,
  0x80, 0x03, 0x00, 0x00,
  0xc0, 0x01, 0x00, 0x00,
  0x60, 0x00, 0x00, 0x00,
  0x20, 0x00, 0x00, 0x00,
  0x10, 0x00, 0x00, 0x00,
  0x18, 0x00, 0x00, 0x00,
  0x08, 0x10, 0x06, 0x00,
  0x0c, 0x70, 0x0f, 0x00,
  0x04, 0xf8, 0x0f, 0x00,
  0x04, 0x78, 0x06, 0x00,
  0x06, 0x20, 0x00, 0x00,
  0x06, 0x80, 0x00, 0x00,
  0x06, 0xc0, 0x01, 0x00,
  0x06, 0xc0, 0x03, 0x00,
  0x0e, 0xe0, 0x01, 0x00,
  0x1c, 0x80, 0x01, 0x00,
  0x1c, 0x00, 0x00, 0x00,
  0x7c, 0x00, 0x00, 0x00,
  0xf8, 0x00, 0x00, 0x00,
  0xf0, 0x07, 0x00, 0x00,
  0xe0, 0x7f, 0x00, 0x3c,
  0xc0, 0xff, 0xff, 0x0f,
  0x00, 0xff, 0xff, 0x01,
  0x00, 0xf0, 0x1f, 0x00,
  0x00, 0x00, 0x00, 0x00};

```

My function for displaying uses Adafruit libraries

```
#include <RGBmatrixPanel.h>
#include <Adafruit_GFX.h>

```

Finally my Function:

```
void xbm32_n (const PROGMEM unsigned char bild[32],word cchsv) {

int i = 0;
while(i<32){

    for(int k=4*i;k<(4+4*i);k++)
    {

    for(int ii = 0; ii<8; ii++){

       int bit = ((pgm_read_byte(&(bild[k]))) >> ii) & 1;
       if(bit == 1) { matrix.drawPixel(ii+8*k-4*8*i, i, cchsv);}}}

   i++   ;
    }
   }

```

The inner workings are as follows:

The function draws each 32 bit row with the color chosen on the Panel depending on the 4 bytes in each "row" of the hex array.

Essentially 2 loops *(to draw the row in byte increments)* with outer while loop *(to move to next row)*. The calculation of the *pixel positions* can be seen inside the `matrix.drawPixel(x-pos,y-pos,color-value)` Adafruit-function, and were made up by experimenting long hours.

See for the whole .ino File here

**Notes on the file**

---

It also features among others

> *(like a displaying shifting 8x8 symbol-array saved in `const PROGMEM byte IMAGES2[][8]` used in the function `bildlauf(1,...)`*

an updated function `void xbm32_4c(char bild[32],word* cchsvar[4], int duration,int cseq[4]))` where:

* `word* cchsvar[4]` points to four color data values
* `cseq[4]` is the sequence for displaying the colors in each panel quadrant

The subdivision of the panel is realized via `if()` and `else if()` commands checking the conditions for positions:
`x = (ii+8*k-4*8*i) </>` *some value*
*&&* `y = i </>` *some value*

---

**Function input:**

* `bild[32]` is used for the hex array as in my case `arab4[]`
* `cchsv` is a color data value . I am using sparkfun 32 LED Matrix and found the following function for hsv color space to work well:

```
  word hsvcolor(int h, int s, int b ) { //Try HSV colors http://colorizer.org/
  int hue1, sat1, bright1;
  word result;

  hue1=map(h, 0, 360, 0, 1535);
  sat1=map(s, 0, 100, 0, 255);
  bright1=map(b, 0, 100, 0, 255);
  result = matrix.ColorHSV(hue1,sat1,bright1,true);

  return result;
}

```

**Current Issues to solve:**

I am using Font Forge to create XBM Files in helping me create the hex letter array, but found it very clumsy to export, as the width size must be a multiple of eight to adjust height by deleting 0x00 rows.

At the moment I am searching for easier ways to "correct" the exported XBM arrays (like using 8x8 Editor 8x8 Editor, only for 32x32 Matrices). Is there a possibility for this?

Alternatively it would also help to create a function to truncate hex arrays to fit 32x32 dimensions somehow.

Additionally, in Arabic there is the issue of variant glyphs for the different letter positions (isolated, medial, initial, final). It seems possible to create byte arrays for all variants but "correcting" each bitmap so that a scrolling effect (I plan to upgrade to 64x32 LED Matrix) "adds up" visually seems daunting. I am happy for suggestion on realizing this challenge as well.

I am aware that there is a Adafruit function for bitmaps: `void Adafruit_GFX::drawBitmap()`
I couldn't get it to work with my hex array, also the possibility on how to change quadrant colors or other subdivisions lead me to write my own version I modified from 8x8 Panel case. I am not sure whether there are inefficiencies in the code I have written, I therefore am happy for suggestions.

# Answer
> 1 votes
The solution to creating Arabic characters with typographic ligature and scrolling them, is:

Using the application *RTB RichText to Bitmap* :

1. Set width-size of bitmap in increments of 32\*n while using a height initially bigger than 32
*(saving the bmp will allow for cropping of rows so that bigger letters can be produced, a bit offset to fit height 32)*
2. Saving the bmp and editing it *(take care that bitmap rows are saved in rows, if not switch scanning line mode)*

Also the byte endian for output must be rightly chosen: *("Lsb" for pc-editing, uploading to arduino for use in the function provided here, it is in "Msb")*
The cropped characters bitmap must be then reloaded into RTB Pixel Editor on a fitting canvas (generate an empty one) and set to a different scanning mode (rows now in columns) with byte endian Msb
3. Group the array of hex elements in pairs of four (you can use notepad++ and
*regex find:* `(((0[xX][0-9a-fA-F,]{2})[,]){3}((0[xX][0-9a-fA-F,]{2})))`
*replace:* `{/1}`

Using a suiting arduino scrolling function (on top of adafruit libraries)

1. Insert 32x(4\_hex) chunks of your bitmap data in the file provided above as array element in:
`const PROGMEM unsigned char
I[][32][4]= {{here},{here},...,{here}}`
2. Adjust *main loop* code for scrolling direction (here r to l) via increment or decrement and number of scrolls (panel-size is here chosen 32):

`int es=64; while (es>0) { scroller01(I,32,dpink,es,go); --es; }`
3. Verify if you need to load a chunk of your bitmap group to `const
PROGMEM unsigned char I[][32][4]` , so that scrolling is fluid and does not jump when the arduino re-cycles

The Question got solved in detour via another question in this exchange (see here ). I am answering it to resolve parts of it.

The scrolling is slow when extended fully onto 64x32 Panels with arduino Mega 2560.
For a clip see:

> www.dropbox.com/s/qth8iuygra1wx9b/VID-20170210-WA0000.mp4?dl=0

If somebody comes up with a more efficient,faster way, please do share!

---
Tags: adafruit, rgb-led
---


title: Regarding PGA bypass in ADS1262

text:
# Question
Title: Regarding PGA bypass in ADS1262
I want to bypass the PGA to change the input signal range from +/-2.5 to 0/5 V range.

I have taken the reference of example given in this library.

I have interfaced protocentral-ads1262-32-bit-precision-adc-breakout-board with Arduino Ethernet Board.

In the example, I have put `#define VREF 5` but it shows the double the input voltage in serial window and when I put `VREF 2.5`, it shows regular input voltage.

For input voltage range 0 to 5V (single signal), I need to bypass the PGA but I dont know how to do it.

When the input signal is more than 2.5V then it always give the 2.5V only. If the input signal is, say 4.86V then it should give 4.86V but its gives 2.5V.

# Answer
You don't want to bypass the PGA.

By default the chip uses the 2.5v internal reference. You need to switch that to using AVDD/AVSS as the voltage reference. If the library doesn't allow that you will have to do it manually referring to the datasheet.
> 1 votes

# Answer
> I want to bypass the PGA to change the input signal range from +/-2.5 to 0/5 V range.

Look at the register map. it should allow you to by pass the pga.

> In the example, I have put #define VREF 5 but it shows the double the input voltage in serial window and when I put VREF 2.5, it shows regular input voltage.

Simple solution: divide the library's output by 2.

Right solution: the library likely doesn't support bipolar output. So re-write your own.
> 0 votes

---
Tags: arduino-uno, programming, analogread
---


title: Bot not activating after button press

text:
# Question
Title: Bot not activating after button press
This bot is supposed to begin moving forward when the button is pressed, and stop after counting 3 lines of tape on the ground. Currently it is set up to scan the color of the floor at the beginning and count any major differences as a line of tape. Unfortunately I can't test its tape-sensing capabilities due to not being able to get it to actually start. It will only move if I hold the button down continuously, and stops as soon as I release it. Here is the code and images (It uses the Arduino Pro Mini 3.3v):

```
#include <SFE_ISL29125.h>
SFE_ISL29125 RGB;
unsigned int master2;
unsigned int detect2;
boolean isOn = false;
unsigned int accumulator = 0;

void setup() {
  RGB.init();
  pinMode(7, INPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  master2 = RGB.readGreen();
}

void loop() {
  if(isOn) {
    if(accumulator < 3) {
      detect2 = RGB.readGreen();
      digitalWrite(8, HIGH);
      digitalWrite(9, LOW);
      if(detect2 <= (master2 - 10) || detect2 >= (master2 + 10)) {
        accumulator++;
      }
    } else {
      accumulator = 0;
      isOn = false;
      digitalWrite(8, LOW);
      digitalWrite(9, LOW);
    }
  } else if(digitalRead(7) == HIGH) {
    isOn = true;
  } else {
    digitalWrite(8, LOW);
    digitalWrite(9, LOW);
  }
}

```

# Answer
I strongly suspect the main problems with your code are in these lines:

```
  if(detect2 <= (master2 - 10) || detect2 >= (master2 + 10)) {
    accumulator++;
  }

```

If I understand correctly, with this code you are attempting to tell whether you have been over a line of tape, which will be indicated by a change in reading from `RGB.readGreen();` \- say high, low, high. If so, `accumulator++`. (I have no opinion on whether this is a valid way of sensing it, or how well your sensor will work.)

This is definitely broken in one way, and probably broken in another.

First the definitely-broken way:

You want to sense down-up-down-up-down-up (or up-down-up-down-up-down). Your code senses simply three higher or lower readings. Your `loop()` takes no time at all, so when your buggy moves onto the tape, it will immediately read (say) high, then loop round, read high again, loop round and read high again, and again. `accumulator` is now 3 and we stop the motor.

Second, the maybe-broken way:

What value does `master2` have? Consider that it is an *unsigned* integer. You are subtracting 10 from it. What do you get if its value is `5`? It can'be be `-5` because it is unsigned. How you solve this depends on the possible range of values from `RGB.readGreen();`. The implementation looks like it could give a value anywhere in the range, so we have to be careful.

Here's my reworking of your code. It assumes the *concept* of checking for values which vary by 10 from the original value is sensible - I've no idea if it is. (I don't understand what this "middle" values means, but you say you've "already tested the components individually" which I don't believe because your code could never have worked but, assuming you saw something similar working...) It also makes a very big assumption that the value will change cleanly - from higher to lower exactly once per edge of strip, with no wobbling. Log out some values to find whether it really does.

```
#include <SFE_ISL29125.h>
SFE_ISL29125 RGB;
int master2;
boolean isOn = false;
int changes = 0;

#define BUTTON 7
#define MOTOR_A 8
#define MOTOR_B 9

#define LOWER 0
#define HIGHER 1
int last_state = 0;

void setup() {
  RGB.init();
  pinMode(BUTTON, INPUT);
  pinMode(MOTOR_A, OUTPUT);
  pinMode(MOTOR_B, OUTPUT);
  master2 = (int)(RGB.readGreen()/2);
}

void loop() {
  if(isOn) {
    // Wait for 6 changes: up-down or down-up, three times.
    if(changes < 6) {
      int detect2 = (int)(RGB.readGreen()/2);
      digitalWrite(MOTOR_A, HIGH);
      digitalWrite(MOTOR_B, LOW);
      // Count _changes_ in state only
      if(last_state == HIGHER && detect2 <= (master2 - 5) {
        last_state = LOWER;
        changes++;
      } else if (last_state == LOWER && detect2 >= (master2 + 5)) {
        last_state = HIGHER;
        changes++;
      }
    } else {
      accumulator = 0;
      isOn = false;
      digitalWrite(MOTOR_A, LOW);
      digitalWrite(MOTOR_B, LOW);
    }
  } else if(digitalRead(7) == HIGH) {
    isOn = true;
  } else {
    digitalWrite(MOTOR_A, LOW);
    digitalWrite(MOTOR_B, LOW);
  }
}

```
> 1 votes

---
Tags: sensors, arduino-nano, motor, button, code-review
---


# Question
Title: Connecting Arduino to internet through HC-06 and then smartphone
Can I use HC-06 to connect the Arduino to a smartphone (which I am already doing) and thereafter take the data to the internet?

# Answer
Yes, but not in quite the way you think.

In this case the smartphone is acting exactly like the PC when you have the Arduino plugged in to it. You have a serial connection. Theoretically you can:

* Send a request to the smartphone over the serial bluetooth connection
* Write some software on the smartphone to interpret that request and perform some action depending on what the request is

That way the smartphone is then acting like an incredibly expensive and bulky ESP8266.
> 1 votes

# Answer
old thread I know..

You can use MIT App Inventor to write/make an app for your Android phone.

This will do several things:

* pair with your Arduino/BT device.
* take data sent from the Arduino/BT device and parse it
* do what you like with that data at that point, save to a database..etc. send info to a map (like google maps)..etc

You havent stated what you want to do with the data after it reaches the phone.

Alternately.. you may be able to get rid of the BT device.. and use an ESP8266 wi-fi module and connect directly to a 3rd party web script/service and dump the data directly to the 'internet'
> 0 votes

---
Tags: arduino-uno, hc-05
---


# Question
Title: New Arduino Motor Shield Short Circuiting my board?
I just got this today, plugged it in my arduino, and the arduino light starts dimming until you cannot see it any more over the course of 5 seconds. The Computer disconnects the arduino when the light is off (Ding Dong Sound). I found pulling the VIN Connector Jumper/Power Jumper will stop the short circuit and work, but that defeats the purpose, as the board wouldn't even powered.

Here is the video: YouTube

Is the motor board broken? If so in what way? are the wires on the board simply broken? Is it due to bad soldering?(I checked solder, looks fine).

Arduino Model: Arduino UNO by Elegoo Motor Driver Model: L293D Driver Board Ebay Listing For Item (I tried using this with a MEGA also, would short it as well).

# Answer
> 0 votes
Thanks to @jwpat7, I have discovered that the reason it is not working is that the seller has messed up and sent me 3 of the same chip, 74HC595N. After doing some research, I have purchased the LM293D Chips.

---
Tags: arduino-uno, arduino-motor-shield
---