text:
Array + Serial Monitor Problem
I've written a Arduino sketch that converts an analogue voltage to a temperature using a lookup table - code below. I've recently changed my LUT to include more values but ever since that my Serial monitor won't print out my debugging statements etc. So I limited the number of elements in the array and it was back to normal. But when I enter more debugging statements using the serial monitor, there is garbage before my statements (still readable though when I parse through it myself) or at the start nothing is printed.
I've checked that the two baud rates are the same but I just find it peculiar that if I take some of my println() statements out it runs okay. Tested everything else with a "Hello World" example but in the simple exaples the monitor works fine.
    /*
    #####PROJECT DESCRIPTION#####
    Measures temperature with an Arduino and NTC Thermistor (10Kohms @ 25^C)                                 in a voltage divider circuit
    Since the response is non-linear, a lookup table is used since there is a non linear response
    The values in the LUT are the predicted values of the ADC at  temperature between 6^C and 40^C
    LUT has been derived from the calibration tests
    */
    //#####CONSTANTS#####
    const int constDelay = 3000; //constant delay for program
    const int constNoOfAnaloguePins = 2; //number of analogue pins that are to be read
    const int errReturn = 998; //error value that is returned ***CHECK FOR CONSITENT VALUE ACROSS FUNCTIONS***
    //#####VARIABLE DECLARATIONS#####
    float avgTempC; //float var to store average of multiple temp readings

    //#####SETUP PROCEDURE#####
    void setup()
    {
      //this is the Setup part of your project - this is for code that is run only ONCE at startup
      for (int analoguePinCounter = 0; analoguePinCounter < constNoOfAnaloguePins; analoguePinCounter++) //for loop to set up numerous analogue pins
      {
        pinMode(analoguePinCounter, INPUT);  //set pin mode of the analogue thermistor input
      }//end for
      analogReference(INTERNAL); //use the interval votlage of 1.1V for the ADC resolution
      Serial.begin(9600); //serial monitor baud rate
    }//end Setup function

    //#####LOOP PROCEDURE#####
    void loop()
    {
      //this is the main part of your project - put all continuously running code here
      for (int analoguePinCounter = 0; analoguePinCounter < constNoOfAnaloguePins; analoguePinCounter++) //for loop to take temp readings from each analogue pin
      {
        //get LPF average reading over 25 samples
        avgTempC = LPF(analoguePinCounter, 25);
        //print out the readings
        if (avgTempC < float(errReturn)) //there hasn't been any temps outside the range ***CHECK THE VALUE RETURNED FROM LPF IF ERROR***
        {
          Serial.print(analoguePinCounter);
          Serial.print(" | Average Temperature Readings = ");
          Serial.print(avgTempC, 2);
          Serial.println(" degC.");
          Serial.println("-------------------------");
        }
        else //avgTempC has returned X indicating an error
        {
          Serial.print(analoguePinCounter);
          Serial.println("**ERROR IN READING AVERAGE TEMP**");
          Serial.println("-------------------------");
          delay(10);
        }//end if
        delay(constDelay/2); //wait X/2 seconds until moving onto next sensor
      }//end for
      delay(constDelay); //wait X seconds until next loop
    }//end Loop function

    /*
    #####LOW PASS FILTER DESCRIPTION#####
    This function is a LPF for smoothing out signals or averaging
    It uses a static buffer to store the last "n" readings, and each time it is called,
    the oldest reading is discarded, the new reading is added, and the stack average
    value is returned.
    The buffer size is user-adjustable, but is constrained between 2 and 50
    An initialization function fills the entire buffer with the input value.
    This is useful when the LPF function is called for the first time.
    Note: To meet the definition of a true LPF, this function must be called         at regular intervals.
    */
    //#####LOW PASS FILTER FUNCTION#####
    float LPF(int pinAnalogue, int bufferSize)
    {
      //##PRE PROCESSOR##
      #define bufferCap 75 //maximum buffer capacity
      //##CONSTANTS##
      const int constMAXERRORS = 5; //max number of error that can occur
      const int errReturn = 998; //value return if there is an error
      //##VARIABLES##
      float tempC; //var to store instantaneous temp
      static float buffer[bufferCap]; //array to act like a 'stack' of temp values ***DOES IT NEED TO BE STATIC NOW?***
      float tempSum; //to store the sum of the temperatures
      float output; //return value of LPF which is the average of the temp readings
      int errCounter = 0; //initialise error counter to 0

      //make sure buffer size is between the range
      bufferSize = constrain(bufferSize, 2, bufferCap);

      for (int i=0; i<bufferSize; i++) //for loop to store temps in buffer array
      {
        tempC = getTempFloat(pinAnalogue); //call function to get temperature from pin
        if ((tempC > -errReturn) && (tempC < errReturn)) //no error
        {
          buffer[i] = tempC; //store temp value into array
        }
        else //error
        {
          errCounter++; //increment counter for number of erroneous readings
          i--; //decrement counter as to not skip a sample index
          if (errCounter > constMAXERRORS)
          {
            return(errReturn+1.0); //return the error value + 1
          }//end if
        }//end if
        delay(25); //allow the ADC to settle
      }//end for

      //calculate current stack average
      tempSum = 0; //initialise sum total
      for (int i=0; i<bufferSize; i++) //go through stack array
      {
        tempSum = tempSum + buffer[i]; //total up readings
      }//end for

      //average sum
      output = tempSum/bufferSize;

      return(output);
    }//end LPF function

    /*
    #####GET TEMP FLOAT DESCRIPTION#####
    This function converts a thermistor reading into a corresponding temp in ^C
    The thermistor is incorporated into a Voltage Divider Circuit:

       +Vref---[Thermistor]---+--[1.8K]---GND
                              |
                             ADC @ thermPin

    ADC Values were externally calculated from the calibration table using:           ADC = 1023*10000/(Rtherm+10000)
    The LUT is an array of integer constants containing the predicted ADC         values for all temperatures between +6^C to +40.5^C.
    The array index starts at zero, which corresponds to a temperature of         +6^C.
    A linear interpolation between the two closest entries is performed to         give a finer output resolution.
    */

    float getTempFloat (int thermPin)
    {
      //##CONSTANTS##
      /*1K8*/
      const int constLUTArraySize = 431;
      const int LUT_Therm[constLUTArraySize] = //LUT containing ADC values
      {
        223, 224, 225, 226, 227, 228, 229, 230, 231, 232,         //7^C to 7.9^C
        233, 234, 235, 236, 237, 238, 239, 240, 241, 242,
        244, 245, 246, 247, 248, 249, 250, 251, 252, 253,
        255, 256, 257, 258, 259, 260, 261, 263, 264, 265,
        266, 267, 268, 269, 271, 272, 273, 274, 275, 277,
        278, 279, 280, 281, 283, 284, 285, 286, 287, 289,
        290, 291, 292, 294, 295, 296, 297, 299, 300, 301,           //13^C to 13.9^C
        302, 304, 305, 306, 308, 309, 310, 312, 313, 314,
        315, 317, 318, 319, 321, 322, 323, 325, 326, 327,
        329, 330, 332, 333, 334, 336, 337, 338, 340, 341,
        343, 344, 345, 347, 348, 350, 351, 353, 354, 355,
        357, 358, 360, 361, 363, 364, 366, 367, 369, 370,
        371, 373, 374, 376, 377, 379, 380, 382, 383, 385,
        387, 388, 390, 391, 393, 394, 396, 397, 399, 400,
        402, 404, 405, 407, 408, 410, 411, 413, 415, 416,
        418, 419, 421, 423, 424, 426, 428, 429, 431, 433,
        434, 436, 438, 439, 441, 443, 444, 446, 448, 449,
        451, 453, 454, 456, 458, 460, 461, 463, 465, 466,
        468, 470, 472, 473, 475, 477, 479, 480, 482, 484,
        486, 488, 489, 491, 493, 495, 497, 498, 500, 502,
        504, 506, 507, 509, 511, 513, 515, 517, 519, 520,
        522, 524, 526, 528, 530, 532, 534, 535, 537, 539,
        541, 543, 545, 547, 549, 551, 553, 555, 557, 559,
        560, 562, 564, 566, 568, 570, 572, 574, 576, 578,
        580, 582, 584, 586, 588, 590, 592, 594, 596, 598,
        600, 602, 604, 606, 608, 611, 613, 615, 617, 619,
        621, 623, 625, 627, 629, 631, 633, 635, 638, 640,
        642, 644, 646, 648, 650, 652, 655, 657, 659, 661,
        663, 665, 667, 670, 672, 674, 676, 678, 680, 683,
        685, 687, 689, 691, 694, 696, 698, 700, 702, 705,
        707, 709, 711, 714, 716, 718, 720, 723, 725, 727,
        729, 732, 734, 736, 738, 741, 743, 745, 747, 750,
        752, 754, 757, 759, 761, 764, 766, 768, 771, 773,
        775, 778, 780, 782, 785, 787, 789, 792, 794, 796,
        799, 801, 803, 806, 808, 811, 813, 815, 818, 820,
        822, 825, 827, 830, 832, 834, 837, 839, 842, 844,
        847, 849, 851, 854, 856, 859, 861, 864, 866, 868,
        871, 873, 876, 878, 881, 883, 886, 888, 891, 893,
        896, 898, 901, 903, 906, 908, 911, 913, 916, 918,
        921, 923, 926, 928, 931, 933, 936, 938, 941, 943,
        946, 948, 951, 953, 956, 958, 961, 963, 966, 969,
        971, 974, 976, 979, 981, 984, 987, 989, 992, 994,
        997, 999, 1002, 1005, 1007, 1010, 1012, 1015, 1017, 1020, //40^C to 49.9^C
        1023                                                     //50^C
      };
      const int errReturn = 998; //error value that is returned
      //##VARIABLES##
      float _tempC; //intermediate results + final temperature return value
      int ADC_Lo; //the lower ADC matching value
      int ADC_Hi; //the higher ADC matching value
      float Temp_Lo; //the lower number matching temperature
      int mapTemp_Lo; //the lower number that will be entered into the map function
      float Temp_Hi; //the higher  number matching temperature
      int mapTemp_Hi; //the higher number that will be entered into the map function

      //prep ADC onto that particular analogue pin to sort out multiplexing etc
      analogRead(thermPin);
      delay(10);
      //get raw ADC value from VDR
      int thermValue = analogRead(thermPin);
      //Serial.println(thermValue);
      /*Serial.print("PinNo : ");
      Serial.println(thermPin);*/
      Serial.print("ADC : ");
      Serial.println(thermValue);
      //return dummy value if the sensor reading falls outside of the LUT
      if (thermValue < LUT_Therm[0]) //less than the least ADC value
        _tempC = -errReturn-1; //under range dummy value
      else if (thermValue > LUT_Therm[constLUTArraySize-1]) //more than the greatest ADC value
        _tempC = errReturn+1; //over range dummy value
      else //value falls in LUT range
      {
        for (int i=0; i<constLUTArraySize; i++) //step through LUT and look for a match
        {
          if (LUT_Therm[i] > thermValue) //LUT value is greater than the reading
          {
            //find the closest higher ADC value
            ADC_Hi = LUT_Therm[i];
            //record the closest higher temperature
            Temp_Hi = float(i/10) + 13.0; //convert to temp
            //get the closest lower temperature - taking the lower table boundary into account
            if (i != 0) //general case -> as long as it is not the first entry
            {
              ADC_Lo = LUT_Therm[i-1]; //store the previous array element as the low
              Temp_Lo = float(i/10) + 13.0 - 0.1; //convert to temp
            }
            else //special case -> counter = 0 ie first array entry
            {
              ADC_Lo = LUT_Therm[i]; //store the first array element
              Temp_Lo = i - float(i/10) + 13.0; //convert to temp
            }//end if
            //interpolate the temperature value for greater precision
            //NB the map function does not use floating-point math, so the int values of temp are multiplied by 100 and then result is subsequently divided by 100
            mapTemp_Lo = Temp_Lo*100;
            mapTemp_Hi = Temp_Hi*100;
            _tempC = float(map(thermValue,ADC_Lo,ADC_Hi,mapTemp_Lo,mapTemp_Hi))/100;
            break;  //exit for loop after the match is detected
          }//end if
        }//end for
      }//end if
      return(_tempC);
    }//end getTempFloat function

In this particular sketch no output is seen on the serial monitor. Has anyone come across this before or have any ideas how I could fix this?

Try putting the data for LUT_Therm in progmem or compressing it somehow

...because it sounds like you have run out of storage space.

Use the F() macro for all double-quoted strings you print.  Change lines like this:
Serial.println(" degC.");

...to this:
Serial.println( F(" degC.") );

This will save about 100 bytes of RAM.
And as BrettAM suggested, put that table into PROGMEM:
  const int LUT_Therm[constLUTArraySize] PROGMEM = //LUT containing ADC values
  {
    223, 224, 225, 226, 227, 228, 229, 230, 231, 232,         //7^C to 7.9^C

This requires changing how you access the array, from this:
  if (thermValue < LUT_Therm[0]) //less than the least ADC value

...to this:
  if (thermValue < (int) pgm_read_word( &LUT_Therm[0] )) //less than the least ADC value

Note the cast, the function call and the ampersand wrapped around the desired array element.  You must replace all uses of the array with this sequence.  You can also read it once into a local int and then use it normally:
      int lut_therm = (int) pgm_read_word(LUT_Therm[i]); // read it in

      if (lut_therm > thermValue) //LUT value is greater than the reading

This saves almost 1000 bytes of RAM!  The reported binary sketch size goes up by the same amount[1].
I had to pull the table out from inside getTempFloat, to the file scope.  Here's the complete sketch with those mods:
/*
#####PROJECT DESCRIPTION#####
Measures temperature with an Arduino and NTC Thermistor (10Kohms @ 25^C)                                 in a voltage divider circuit
Since the response is non-linear, a lookup table is used since there is a non linear response
The values in the LUT are the predicted values of the ADC at  temperature between 6^C and 40^C
LUT has been derived from the calibration tests
*/

//#####CONSTANTS#####
const int constDelay = 3000; //constant delay for program
const int constNoOfAnaloguePins = 2; //number of analogue pins that are to be read
const int errReturn = 998; //error value that is returned ***CHECK FOR CONSITENT VALUE ACROSS FUNCTIONS***

//#####VARIABLE DECLARATIONS#####
float avgTempC; //float var to store average of multiple temp readings

//#####SETUP PROCEDURE#####
void setup()
{
  //this is the Setup part of your project - this is for code that is run only ONCE at startup
  for (int analoguePinCounter = 0; analoguePinCounter < constNoOfAnaloguePins; analoguePinCounter++) //for loop to set up numerous analogue pins
  {
    pinMode(analoguePinCounter, INPUT);  //set pin mode of the analogue thermistor input
  }//end for
  analogReference(INTERNAL); //use the interval votlage of 1.1V for the ADC resolution
  Serial.begin(9600); //serial monitor baud rate
}//end Setup function

//#####LOOP PROCEDURE#####
void loop()
{
  //this is the main part of your project - put all continuously running code here
  for (int analoguePinCounter = 0; analoguePinCounter < constNoOfAnaloguePins; analoguePinCounter++) //for loop to take temp readings from each analogue pin
  {
    //get LPF average reading over 25 samples
    avgTempC = LPF(analoguePinCounter, 25);
    //print out the readings
    if (avgTempC < float(errReturn)) //there hasn't been any temps outside the range ***CHECK THE VALUE RETURNED FROM LPF IF ERROR***
    {
      Serial.print(analoguePinCounter);
      Serial.print( F(" | Average Temperature Readings = ") );
      Serial.print(avgTempC, 2);
      Serial.println( F(" degC.") );
      Serial.println( F("-------------------------") );
    }
    else //avgTempC has returned X indicating an error
    {
      Serial.print(analoguePinCounter);
      Serial.println( F("**ERROR IN READING AVERAGE TEMP**") );
      Serial.println( F("-------------------------") );
      delay(10);
    }//end if
    delay(constDelay/2); //wait X/2 seconds until moving onto next sensor
  }//end for
  delay(constDelay); //wait X seconds until next loop
}//end Loop function

/*
#####LOW PASS FILTER DESCRIPTION#####
This function is a LPF for smoothing out signals or averaging
It uses a static buffer to store the last "n" readings, and each time it is called,
the oldest reading is discarded, the new reading is added, and the stack average
value is returned.
The buffer size is user-adjustable, but is constrained between 2 and 50
An initialization function fills the entire buffer with the input value.
This is useful when the LPF function is called for the first time.
Note: To meet the definition of a true LPF, this function must be called         at regular intervals.
*/
//#####LOW PASS FILTER FUNCTION#####
float LPF(int pinAnalogue, int bufferSize)
{
  //##PRE PROCESSOR##
  #define bufferCap 75 //maximum buffer capacity
  //##CONSTANTS##
  const int constMAXERRORS = 5; //max number of error that can occur
  //##VARIABLES##
  float tempC; //var to store instantaneous temp
  static float buffer[bufferCap]; //array to act like a 'stack' of temp values ***DOES IT NEED TO BE STATIC NOW?***
  float tempSum; //to store the sum of the temperatures
  float output; //return value of LPF which is the average of the temp readings
  int errCounter = 0; //initialise error counter to 0

  //make sure buffer size is between the range
  bufferSize = constrain(bufferSize, 2, bufferCap);

  for (int i=0; i<bufferSize; i++) //for loop to store temps in buffer array
  {
    tempC = getTempFloat(pinAnalogue); //call function to get temperature from pin
    if ((tempC > -errReturn) && (tempC < errReturn)) //no error
    {
      buffer[i] = tempC; //store temp value into array
    }
    else //error
    {
      errCounter++; //increment counter for number of erroneous readings
      i--; //decrement counter as to not skip a sample index
      if (errCounter > constMAXERRORS)
      {
        return(errReturn+1.0); //return the error value + 1
      }//end if
    }//end if
    delay(25); //allow the ADC to settle
  }//end for

  //calculate current stack average
  tempSum = 0; //initialise sum total
  for (int i=0; i<bufferSize; i++) //go through stack array
  {
    tempSum = tempSum + buffer[i]; //total up readings
  }//end for

  //average sum
  output = tempSum/bufferSize;

  return(output);
}//end LPF function

/*
#####GET TEMP FLOAT DESCRIPTION#####
This function converts a thermistor reading into a corresponding temp in ^C
The thermistor is incorporated into a Voltage Divider Circuit:

   +Vref---[Thermistor]---+--[1.8K]---GND
                          |
                         ADC @ thermPin

ADC Values were externally calculated from the calibration table using:           ADC = 1023*10000/(Rtherm+10000)
The LUT is an array of integer constants containing the predicted ADC         values for all temperatures between +6^C to +40.5^C.
The array index starts at zero, which corresponds to a temperature of         +6^C.
A linear interpolation between the two closest entries is performed to         give a finer output resolution.
*/

//##CONSTANTS##
/*1K8*/
const int LUT_Therm[] PROGMEM = //LUT containing ADC values
{
  223, 224, 225, 226, 227, 228, 229, 230, 231, 232,         //7^C to 7.9^C
  233, 234, 235, 236, 237, 238, 239, 240, 241, 242,
  244, 245, 246, 247, 248, 249, 250, 251, 252, 253,
  255, 256, 257, 258, 259, 260, 261, 263, 264, 265,
  266, 267, 268, 269, 271, 272, 273, 274, 275, 277,
  278, 279, 280, 281, 283, 284, 285, 286, 287, 289,
  290, 291, 292, 294, 295, 296, 297, 299, 300, 301,           //13^C to 13.9^C
  302, 304, 305, 306, 308, 309, 310, 312, 313, 314,
  315, 317, 318, 319, 321, 322, 323, 325, 326, 327,
  329, 330, 332, 333, 334, 336, 337, 338, 340, 341,
  343, 344, 345, 347, 348, 350, 351, 353, 354, 355,
  357, 358, 360, 361, 363, 364, 366, 367, 369, 370,
  371, 373, 374, 376, 377, 379, 380, 382, 383, 385,
  387, 388, 390, 391, 393, 394, 396, 397, 399, 400,
  402, 404, 405, 407, 408, 410, 411, 413, 415, 416,
  418, 419, 421, 423, 424, 426, 428, 429, 431, 433,
  434, 436, 438, 439, 441, 443, 444, 446, 448, 449,
  451, 453, 454, 456, 458, 460, 461, 463, 465, 466,
  468, 470, 472, 473, 475, 477, 479, 480, 482, 484,
  486, 488, 489, 491, 493, 495, 497, 498, 500, 502,
  504, 506, 507, 509, 511, 513, 515, 517, 519, 520,
  522, 524, 526, 528, 530, 532, 534, 535, 537, 539,
  541, 543, 545, 547, 549, 551, 553, 555, 557, 559,
  560, 562, 564, 566, 568, 570, 572, 574, 576, 578,
  580, 582, 584, 586, 588, 590, 592, 594, 596, 598,
  600, 602, 604, 606, 608, 611, 613, 615, 617, 619,
  621, 623, 625, 627, 629, 631, 633, 635, 638, 640,
  642, 644, 646, 648, 650, 652, 655, 657, 659, 661,
  663, 665, 667, 670, 672, 674, 676, 678, 680, 683,
  685, 687, 689, 691, 694, 696, 698, 700, 702, 705,
  707, 709, 711, 714, 716, 718, 720, 723, 725, 727,
  729, 732, 734, 736, 738, 741, 743, 745, 747, 750,
  752, 754, 757, 759, 761, 764, 766, 768, 771, 773,
  775, 778, 780, 782, 785, 787, 789, 792, 794, 796,
  799, 801, 803, 806, 808, 811, 813, 815, 818, 820,
  822, 825, 827, 830, 832, 834, 837, 839, 842, 844,
  847, 849, 851, 854, 856, 859, 861, 864, 866, 868,
  871, 873, 876, 878, 881, 883, 886, 888, 891, 893,
  896, 898, 901, 903, 906, 908, 911, 913, 916, 918,
  921, 923, 926, 928, 931, 933, 936, 938, 941, 943,
  946, 948, 951, 953, 956, 958, 961, 963, 966, 969,
  971, 974, 976, 979, 981, 984, 987, 989, 992, 994,
  997, 999, 1002, 1005, 1007, 1010, 1012, 1015, 1017, 1020, //40^C to 49.9^C
  1023                                                     //50^C
};
const int constLUTArraySize = sizeof(LUT_Therm)/sizeof(LUT_Therm[0]);

float getTempFloat (int thermPin)
{
  //##VARIABLES##
  float _tempC; //intermediate results + final temperature return value
  int ADC_Lo; //the lower ADC matching value
  int ADC_Hi; //the higher ADC matching value
  float Temp_Lo; //the lower number matching temperature
  int mapTemp_Lo; //the lower number that will be entered into the map function
  float Temp_Hi; //the higher  number matching temperature
  int mapTemp_Hi; //the higher number that will be entered into the map function

  //prep ADC onto that particular analogue pin to sort out multiplexing etc
  analogRead(thermPin);
  delay(10);
  //get raw ADC value from VDR
  int thermValue = analogRead(thermPin);
  //Serial.println(thermValue);
  /*Serial.print( F("PinNo : ") );
  Serial.println(thermPin);*/
  Serial.print( F("ADC : ") );
  Serial.println(thermValue);

  //return dummy value if the sensor reading falls outside of the LUT
  if (thermValue < (int) pgm_read_word( &LUT_Therm[0] )) //less than the least ADC value
    _tempC = -errReturn-1; //under range dummy value

  else if (thermValue > (int) pgm_read_word(LUT_Therm[constLUTArraySize-1])) //more than the greatest ADC value
    _tempC = errReturn+1; //over range dummy value

  else //value falls in LUT range
  {
    int prev_lut_therm = 0;
    for (int i=0; i<constLUTArraySize; i++) //step through LUT and look for a match
    {
      int lut_therm = (int) pgm_read_word(LUT_Therm[i]);
      if (lut_therm > thermValue) //LUT value is greater than the reading
      {
        //find the closest higher ADC value
        ADC_Hi = lut_therm;
        //record the closest higher temperature
        Temp_Hi = float(i/10) + 13.0; //convert to temp
        //get the closest lower temperature - taking the lower table boundary into account
        if (i != 0) //general case -> as long as it is not the first entry
        {
          ADC_Lo = prev_lut_therm; //store the previous array element as the low
          Temp_Lo = float(i/10) + 13.0 - 0.1; //convert to temp
        }
        else //special case -> counter = 0 ie first array entry
        {
          ADC_Lo = lut_therm; //store the first array element
          Temp_Lo = i - float(i/10) + 13.0; //convert to temp
        }//end if
        //interpolate the temperature value for greater precision
        //NB the map function does not use floating-point math, so the int values of temp are multiplied by 100 and then result is subsequently divided by 100
        mapTemp_Lo = Temp_Lo*100;
        mapTemp_Hi = Temp_Hi*100;
        _tempC = float(map(thermValue,ADC_Lo,ADC_Hi,mapTemp_Lo,mapTemp_Hi))/100;
        break;  //exit for loop after the match is detected
      }//end if
      prev_lut_therm = lut_therm;
    }//end for
  }//end if
  return(_tempC);
}//end getTempFloat function

Note the technique for declaring the LUT_Therm array, using the empty [] brackets (line 135).
That's followed by the const int array size (line 182) that is "calculated" from the array declaration: (Total array size) / (size of one array element).  If you ever change the lookup table, you don't have to count the elements by hand.  Let the compiler do it for you!  :)

[1] Although the IDE reports an increased binary sketch size, the total uploaded size is unchanged:

PROGMEM keyword   text    data     bss
No                5948     894     483
Yes               6810      32     483

As you can see, the 862 bytes for this table move from the data section to the text section.  The uploaded HEX files are identical at 93,737 bytes.

I have a page about putting things into PROGMEM.

“The binary sketch size goes up by the same amount”. That's wrong. Initialized arrays eat the same amount of flash whether they are PROGMEM or not.

@EdgarBonet, true, but the reported program size goes up by the same amount.  Try it!  :)  Just delete the PROGMEM keyword.  Although it wouldn't run correctly, the size reported in build log changes.  Must have something to do with which sections get added up?

...now I'm wondering which number is correct...

Your avr-size must be broken. With PROGMEM I get a program size of 6646 bytes (.text: 6604 bytes, .data: 42 bytes). If I remove PROGMEM I get 6644 bytes (.text: 5606, .data: 1038). I checked the HEX file size (the stuff that is actually transferred to the Arduino flash) and in both cases the reported program size is correct. Please fix your answer.

@EdgarBonet, my avr-size is not broken.  Perhaps the IDE does not report as you expected.  I have added a footnote with details to address your comment.  It is an artifact of how the IDE adds the sections, as I suspected.

You have likely run out of RAM.
You have 431 integers in the look-up table alone. That equates to 862 bytes of SRAM. You also have a buffer of 75 floats, which equates to 300 bytes. This is in addition to all your other variables and function calls.
The Arduino Uno only has 2KB of SRAM.
Solutions:
 1) Move your LUT to Flash (ie. program space) using the PROGMEM keyword (just before the equals sign):
const int LUT_Therm[constLUTArraySize] PROGMEM = //LUT containing ADC values

2) Use an Arduino with a greater amount of SRAM.

Arduino Mega  - 8KB SRAM
Arduino ZERO  - 32KB SRAM
Arduino Due   - 96KB SRAM
Arduino MKR 1000/1010/1400/ZERO - 32KB SRAM

I went through your program and found a few bugs you may want to fix. I
think only one of these (wastage of RAM) is really related to your
problem, but anyway, here it goes:
Fist, there are two issues with LPF(). The description states that
this is a rolling average low-pass filter. This is erroneous: a rolling
average would take a single reading, then report the average of the
last n readings. This function, in contrast, takes n readings and
reports their average. This makes a big difference: a rolling average
would need to store the last n values in static memory, while your
function does this for no good reason. You are just wasting
300 bytes of RAM.
Here is a reimplementation of LPF() that does the same thing as yours
without wasting RAM. I changed its name to be more consistent with it's
real purpose:
/*
 * Take 'count' temperature readings from 'pin' and return their average.
 * Returns NaN (not a number) if too many readings where in error.
 */
float getAvgTemp(int pin, int count)
{
  const int MAXERRORS = 5; // max number of errors that can occur
  float temp;              // current temperature reading
  float tempSum = 0;       // sum of temperatures
  int errCounter = 0;      // number of erroneous readings

  for (int i = 0; i < count; i++) {

    // Try to get a valid reading.
    do {
      temp = getTempFloat(pin);
      if (isnan(temp))
        errCounter++;
      delay(25); // allow the ADC to settle
    } while (isnan(temp) && errCounter <= MAXERRORS);

    // Too many errors: return an error.
    if (errCounter > MAXERRORS)
      return NAN;

    tempSum += temp;
  }

  return tempSum / count;
}

Here I use NaN (not a number) as an error indicator, as it is
semantically clearer than a random out-of-range value.
There are also a few errors in getTempFloat():

pgm_read_word(LUT_Therm[constLUTArraySize-1]) and
pgm_read_word(LUT_Therm[i]) will not work: you have to pass
pgm_read_word() the address where to read.
float(i/10) does not do what you want: it computes i/10 as an
integer division (i.e. discarding the fractional part), and then it
converts the result to a float. If you want a floating point division,
you should make sure that at least one of the arguments is a float.
The usual idiom is i/10.0.

Here is a version of getTempFloat() with these problems fixed, and
also somewhat simplified:
float getTempFloat(int pin)
{
  int i, lutval, prev_lutval;

  // Take an analog reading.
  analogRead(pin);  // dummy reading to settle the MUX
  delay(10);
  int adc = analogRead(pin);
  Serial.print(F("ADC: "));
  Serial.println(adc);

  // Find i such that adc lies between LUT[i-1] and LUT[i].
  for (i = 0; i < constLUTArraySize; i++) {
    prev_lutval = lutval;
    lutval = pgm_read_word(&LUT_Therm[i]);
    if (lutval >= adc) break;
  }

  // Special case: adc == LUT[0].
  if (i == 0 && adc == lutval)
    return 13.0;

  // Report an error if out of range.
  if (i == 0 || i == constLUTArraySize)
    return NAN;

  // Return interpolated temperature.
  float fraction = float(adc - prev_lutval) / (lutval - prev_lutval);
  return 13.0 + (i-1 + fraction) / 10.0;
}

Addendum
I have noticed a few more problems and inconsistencies with your
program.
Powering the thermistor from the internal reference
In setup(), you write

analogReference(INTERNAL); //use the interval votlage of 1.1V for the
  ADC resolution

and then, in a comment further down you have the schematic

+Vref---[Thermistor]---+--[1.8K]---GND

This suggests you are powering the voltage divider from the internal
voltage reference of the MCU. You should not do that, as the datasheet
states: “Note that VREF is a high impedance source, and only
a capacitive load should be connected in a system.”
Relationship between ADC reading and thermistor resistance
In the same comment as above, you wrote:

ADC = 1023*10000/(Rtherm+10000)

Actually, the factor is 1024, not 1023. Again, see the datasheet. And
the number 10000 should be 1800, i.e. the resistance you have put
between the ADC input and GND. I understand that you may have simply
changed the value and forgotten to update one of the comments. But you
should consider a misleading comment as a bug, especially if it's not
consistent with the actual code.
For this kind of measurement, you get the best precision if the pulldown
resistor has a value close to the resistance of the thermistor. The
comment at the beginning of the program says your thermistor has
10 kΩ @ 25°C. This means that, if you are mostly interested in
the range around 25°C, a 10 kΩ pulldown is better than 1.8 kΩ.
Relationship between array index and temperature
The comment before the LUT says:

The array index starts at zero, which corresponds to a temperature of
  +6^C

Then, the very first line of the LUT has the comment

//7^C to 7.9^C

And later on, the implementation of getTempFloat() assumes
index 0 means 13°C. You should sort this out and make everything
consistent.
BTW, your LUT values go all the way up to 1023. A reading of 1023 would
mean the ADC voltage is higher than 1022.5/1024×VREF. Which
in turn would imply the thermistor has a resistance lower than
14.6 Ω (assuming a 10 kΩ pulldown). I find this dubious.
Removal of the LUT
Since your program is meant to run very slowly (constDelay = 3000),
you can afford doing complex computations in it. You can get the same
precision with a way smaller LUT if you use a higher order
interpolation. For a function sampled at constant steps, the
Catmull–Rom
spline
is easy to implement and is way better than linear interpolation.
Or you can remove the LUT altogether and use an analytical expression
instead. If you derived the LUT from such an expression, why not use it
in the program? If the LUT derives from experimental data, you can try
to do an empirical fit, i.e. an arbitrary function that closely fits the
data. The most obvious (though maybe not the best) empirical function
would be a polynomial. Below is an example of such a function that
reproduces you LUT with good accuracy using a 6th degree polynomial. It
assumes the first LUT entry is for a temperature of 7°C:
float getTempFloat(int pin)
{
    const float T0 = 7;   // temperature at beginning of range
    int adc = analogRead(pin);
    float x = (adc-223.) / (1023.-223.) * 2 - 1;  // scale to [-1:1]
    if (x < -1 || x > 1) return NAN;              // out of range
    float y = 1.474 - x*(0.533 - x*(0.732 - x*0.458));
    return T0 + 26.107 + x*(19.287 - x*(3.596 - x*y));
}

Actually this may be even more accurate than your LUT-based function, as
that LUT is made of integer values whereas the calibration curve should
obviously be continuous.

Many thanks for your points some I wouldn't have considered. Yeah I've been changing the temp range so some comments don't make sense. Is the analogReference(Internal) call not use the 1.1V to get a better resolution between ADC steps and by using the Arduino's 3.3V power out as Vref and I've worked out that a 1k8ohm resistor gives me a range of 7-50degC (however as shown above I may be wrong!). I'm using this as a skin temperature logger so temps will be in the range of 30-40degC. I'm still unsure of how many measurements per minute I want but the interpolation looks nicer. Thanks


text:
Need to make an action just once when condition is reached
I'm making a device for the visually disabled that makes a sound when the water in a bowl reach certain levels.
I've already made the sensors for three levels of water and if statements to make the sound, but I need the sound to be played just once for every level change and it loops over and over.
How can I make it to sound just one time?
Here is my code:
#include <PCM.h>
const unsigned char sample[] PROGMEM = { //Here goes the sample
};
int low = 0;
int mid = 0;
int high = 0;

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

}

void loop() {
  // put your main code here, to run repeatedly:
  low = analogRead(A0);
  mid = analogRead(A1);
  high = analogRead(A2);
  Serial.print("nivel agua: ");

  if (high > 50){
    Serial.print("Alto");
    startPlayback(sample, sizeof(sample));
  }
  else if (mid >50){
    Serial.print("Medio");
    startPlayback(sample, sizeof(sample));
  }
  else if (low > 50){
    Serial.print("Bajo");
    startPlayback(sample, sizeof(sample));
  }
  delay(100);

Have you ever think to use a boolean flag variable?

A possible solution to your problem can be the following:
#include <PCM.h>
const unsigned char sample[] PROGMEM = { //Here goes the sample
};
int low = 0;
int mid = 0;
int high = 0;
bool first = true;
bool second = true;
bool third = true;

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

}

void loop() {
  // put your main code here, to run repeatedly:
  low = analogRead(A0);
  mid = analogRead(A1);
  high = analogRead(A2);
  Serial.print("nivel agua: ");

  if (high > 50 && first){
    Serial.print("Alto");
    startPlayback(sample, sizeof(sample));
    first = false;
  }
  else if (mid >50 && second){
    Serial.print("Medio");
    startPlayback(sample, sizeof(sample));
    second = false;
  }
  else if (low > 50 && third){
    Serial.print("Bajo");
    startPlayback(sample, sizeof(sample));
    third = false;
  }
  delay(100);

In this way the sound for each level will be played only once. I hope this is what you were looking for.

Thank you!!, never came to my mind. I also added that when one flag comes false the others come true so i can go up and down

@Mattia I've added an answer that includes my thoughts on speed. I'll delete my other comments to avoid having double-information and a garbage in the comment section.

As an addition to the answer of Mattia.
I suspect you have something like:
void loop() {
  // put your main code here, to run repeatedly:
  low = analogRead(A0);
  mid = analogRead(A1);
  high = analogRead(A2);
  Serial.print("nivel agua: ");

  if (resetVariables){
     first = true;
     second = true;
     third = true;
     resetVariables = false;
  }

  if (high > 50 && first){
    Serial.print("Alto");
    startPlayback(sample, sizeof(sample));
    first = false;
  }
  else if (mid >50 && second){
    Serial.print("Medio");
    startPlayback(sample, sizeof(sample));
    second = false;
  }
  else if (low > 50 && third){
    Serial.print("Bajo");
    startPlayback(sample, sizeof(sample));
    third = false;
  }

  if(buttonPressed){
    resetVariables = true;
  }
  delay(100);
}

A better practice would be to use another function
void resetFlags() {
  first = true;
  second = true;
  third = true;
}

And the main code would be:
void loop() {
  // put your main code here, to run repeatedly:
  low = analogRead(A0);
  mid = analogRead(A1);
  high = analogRead(A2);
  Serial.print("nivel agua: ");

  if (high > 50 && first){
    Serial.print("Alto");
    startPlayback(sample, sizeof(sample));
    first = false;
  }
  else if (mid >50 && second){
    Serial.print("Medio");
    startPlayback(sample, sizeof(sample));
    second = false;
  }
  else if (low > 50 && third){
    Serial.print("Bajo");
    startPlayback(sample, sizeof(sample));
    third = false;
  }

  if(buttonPressed){
    resetFlags();
  }
  delay(100);
}

Would this be faster?

It would at least make your loop code more readable, instead of juggling flags around.
resetFlags(); would act immediately and independent from the flag checking etc.
It saves checking unnecessary if's (which equals a very little speed increase).
It saves 1 boolean (byte maximal in memory) which equals a very little memory/speed increase.

But why mind speed if you have a 100msec delay?
You could make it only output the water level when it changes. Then you can run the water checking extremely fast!
(It wouldn't spam your console, plus, writing to console takes considerable amount of time, compared to checking if's.)

source: Stack Exchange

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

sort: votes


text:
How to use TimerOne while calculating time?
I'm trying to get warning with buzzer while I get same values on 3 seconds. But first warning doesn't wait 3 seconds. Second warning is correct. Code is attached. BlinkLED1() method is same BlinkLED2. Probably, I'm missing crowning touch. Can you help me?
Thanks in advance.
void initialsettings(double roll,double pitch){
  if(level==0){
    if(roll>=34 && timerstatus==false){

        Timer1.initialize(3000000);
        timerstatus=true;
        Timer1.attachInterrupt(blinkLED);
    } else{
         Timer1.stop();
         timerstatus=false;
         level=0;
    }

   }else if(level==1){
      if(roll<=-34 && timerstatus==false){

        Timer1.initialize(3000000);
        timerstatus=true;
         Timer1.attachInterrupt(blinkLED2);
      } else{
           Timer1.stop();
         timerstatus=false;

      }

  }else if(level==2){

  }
}

void blinkLED(void)
{
    noInterrupts();
    Timer1.stop();

    //Timer1.restart();
    digitalWrite(buzzerpin,HIGH);
    delay(7000);
    digitalWrite(buzzerpin,LOW);
    timerstatus=false;
    interrupts();
    if(level==0){
      level=1;
      Serial.println("level 1");
    }
  Serial.println("Sag ");
    //Serial.print("\n");

}

    Timer1.attachInterrupt(blinkLED);

...
void blinkLED(void)
{
    noInterrupts();
    Timer1.stop();

    //Timer1.restart();
    digitalWrite(buzzerpin,HIGH);
    delay(7000);
    digitalWrite(buzzerpin,LOW);
    timerstatus=false;
    interrupts();
    if(level==0){
      level=1;
      Serial.println("level 1");
    }
  Serial.println("Sag ");

Don't do serial prints inside an interrupt service routine (ISR).
Don't use delay() inside an ISR.
Don't turn interrupts on or off inside an ISR.
Variables shared between an ISR and the main code should be volatile (I can't see from your snippet whether they are or not).

Reference: Interrupts

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


text:
Bluetooth shield with ardudroid RGB LED
Here is their code:
/*
 PROJECT: ArduDroid
 PROGRAMMER: Hazim Bitar (techbitar at gmail dot com)
 DATE: Oct 31, 2013
 FILE: ardudroid.ino
 LICENSE: Public domain
*/

#define START_CMD_CHAR '*'
#define END_CMD_CHAR '#'
#define DIV_CMD_CHAR '|'
#define CMD_DIGITALWRITE 10
#define CMD_ANALOGWRITE 11
#define CMD_TEXT 12
#define CMD_READ_ARDUDROID 13
#define MAX_COMMAND 20  // max command number code. used for error checking.
#define MIN_COMMAND 10  // minimum command number code. used for error checking.
#define IN_STRING_LENGHT 40
#define MAX_ANALOGWRITE 255
#define PIN_HIGH 3
#define PIN_LOW 2

String inText;

void setup() {
  Serial.begin(9600);
  Serial.println("ArduDroid 0.12 Alpha by TechBitar (2013)");
  Serial.flush();
}

void loop()
{
  Serial.flush();
  int ard_command = 0;
  int pin_num = 0;
  int pin_value = 0;

  char get_char = ' ';  //read serial

  // wait for incoming data
  if (Serial.available() < 1) return; // if serial empty, return to loop().

  // parse incoming command start flag
  get_char = Serial.read();
  if (get_char != START_CMD_CHAR) return; // if no command start flag, return to loop().

  // parse incoming command type
  ard_command = Serial.parseInt(); // read the command

  // parse incoming pin# and value
  pin_num = Serial.parseInt(); // read the pin
  pin_value = Serial.parseInt();  // read the value

  // 1) GET TEXT COMMAND FROM ARDUDROID
  if (ard_command == CMD_TEXT){
    inText =""; //clears variable for new input
    while (Serial.available())  {
      char c = Serial.read();  //gets one byte from serial buffer
      delay(5);
      if (c == END_CMD_CHAR) { // if we the complete string has been read
        // add your code here
        break;
      }
      else {
        if (c !=  DIV_CMD_CHAR) {
          inText += c;
          delay(5);
        }
      }
    }
  }

  // 2) GET digitalWrite DATA FROM ARDUDROID
  if (ard_command == CMD_DIGITALWRITE){
    if (pin_value == PIN_LOW) pin_value = LOW;
    else if (pin_value == PIN_HIGH) pin_value = HIGH;
    else return; // error in pin value. return.
    set_digitalwrite( pin_num,  pin_value);  // Uncomment this function if you wish to use
    return;  // return from start of loop()
  }

  // 3) GET analogWrite DATA FROM ARDUDROID
  if (ard_command == CMD_ANALOGWRITE) {
    analogWrite(  pin_num, pin_value );
    // add your code here
    return;  // Done. return to loop();
  }

  // 4) SEND DATA TO ARDUDROID
  if (ard_command == CMD_READ_ARDUDROID) {
    // char send_to_android[] = "Place your text here." ;
    // Serial.println(send_to_android);   // Example: Sending text
    Serial.print(" Analog 0 = ");
    Serial.println(analogRead(A0));  // Example: Read and send Analog pin value to Arduino
    return;  // Done. return to loop();
  }
}

// 2a) select the requested pin# for DigitalWrite action
void set_digitalwrite(int pin_num, int pin_value)
{
  switch (pin_num) {
  case 13:
    pinMode(13, OUTPUT);
    digitalWrite(13, pin_value);
    // add your code here
    break;
  case 12:
    pinMode(12, OUTPUT);
    digitalWrite(12, pin_value);
    // add your code here
    break;
  case 11:
    pinMode(11, OUTPUT);
    digitalWrite(11, pin_value);
    // add your code here
    break;
  case 10:
    pinMode(10, OUTPUT);
    digitalWrite(10, pin_value);
    // add your code here
    break;
  case 9:
    pinMode(9, OUTPUT);
    digitalWrite(9, pin_value);
    // add your code here
    break;
  case 8:
    pinMode(8, OUTPUT);
    digitalWrite(8, pin_value);
    // add your code here
    break;
  case 7:
    pinMode(7, OUTPUT);
    digitalWrite(7, pin_value);
    // add your code here
    break;
  case 6:
    pinMode(6, OUTPUT);
    digitalWrite(6, pin_value);
    // add your code here
    break;
  case 5:
    pinMode(5, OUTPUT);
    digitalWrite(5, pin_value);
    // add your code here
    break;
  case 4:
    pinMode(4, OUTPUT);
    digitalWrite(4, pin_value);
    // add your code here
    break;
  case 3:
    pinMode(3, OUTPUT);
    digitalWrite(3, pin_value);
    // add your code here
    break;
  case 2:
    pinMode(2, OUTPUT);
    digitalWrite(2, pin_value);
    // add your code here
    break;
    // default:
    // if nothing else matches, do the default
    // default is optional
  }
}

And a photo of my circuit:

Is anyone able to tell me why when the ardudroid app and bluetooth shield are linked successfully, my LED won't respond to the commands on the app?

Please take a look at the formatting help: http://arduino.stackexchange.com/editing-help


text:
Adapt Dynamixel library to different shields
I have been playing around with this shield for a couple of days now and I have to agree with some statements made in the comments that the "library" lacks many functions.
However I have discovered the following library which was built for the Dynamixel shield: https://github.com/zcshiner/Dynamixel_Serial
I wanted to know since I am using an Arduino Uno, which parameters I would have to change to make it work.
Sorry I am not very fluent in C++. I have tried just changing the direction pin to 10 but it's obviously not sufficient.
Shield to be dealt with: https://dfrobot.com/index.php?route=product/product&product_id=958
The following code should work afterwards:
#include <dynamixel_serial.h> // Library needed to control Dynamixel servo

#define SERVO_ID 0x01 // ID which we will set Dynamixel to
#define SERVO_ControlPin 0x0A // Control pin of buffer chip, NOTE: this does not matter because we are not using a half to full control buffer.
#define SERVO_SET_Baudrate 57600 // Baud rate speed which the Dynamixel will be set to (57600)
#define CW_LIMIT_ANGLE 0x001 // lowest clockwise angle is 1, as when set to 0 it sets servo to wheel mode
#define CCW_LIMIT_ANGLE 0xFFF // Highest anti-clockwise angle is 0XFFF, as when set to 0 it sets servo to wheel mode

void setup() {
  delay(1000); // Give time for Dynamixel to start on power-up
  Dynamixel.begin(SERVO_SET_Baudrate); // We now need to set Arduino to the new baud rate speed
  Dynamixel.setDirectionPin(SERVO_ControlPin); // Optional. Set direction control pin
  Dynamixel.setMode(SERVO_ID, SERVO, CW_LIMIT_ANGLE, CCW_LIMIT_ANGLE); // set mode to SERVO and set angle limits
  Serial.begin(115200);
  Serial.println("Setup Done!");
  pinMode(13, OUTPUT);
}

void loop() {
  digitalWrite(13, HIGH);
  Dynamixel.servo(SERVO_ID,0x001,0x100); // Move servo to angle 1(0.088 degree) at speed 100
  delay(4000);
  Dynamixel.servo(SERVO_ID,0xFFF,0x3FF); // Move servo to max angle at max speed (1023)
  delay(4000);
}

You are setting the baudrate to 57.6K however, you need to communicate with the Dynamixel at the baudrate it is set to. I believe the Dynamixel comes with a preset baudrate of 1Mbs. The first thing thing I would do is to change your 57.6K to 1Mbs and try that. This is assuming the ID is actually 1 (also a default)
Here are two links for info on Arduino baud rates and Dynamixel serial communications.
Controlling AX-12 Servos
How high of a baud rate can I go (without errors)?

Thank you very much I am going to try as soon as I have got the possiblitiy


text:
Dshot implementation on Arduino (ESC protocol)
Does anyone one know if it's possible to implement Dshot on Arduino? I want to interface the Arduino with ESCs (electric speed controllers). These ESCs use Dshot,
 (https://oscarliang.com/dshot/) a digital protocol. From what I read online, you can make PWM follow a duty cycle. However, I want to change the duty cycle after each pulse and not just repeat the same duty cycle. I understand this requires DMA (direct memory access) but it's a bit over my head.

There is no technical specification of "dshot" at your link, only an advertisement

The more important question however is how you would get any actual benefit - this is a high performance protocol for fast control loops run on fast modern processors, not slow, limited ATmegas.  Pretty much any ESC that supports this supports other things too, either automatically or with a different build of the open firmware it is using to support this in the first place.

I mainly want dshot for everything except the performance aspect (send commands, beeping, telemetry,  leds, parity bits). I don't mind using pwm but since I'm getting this esc anyway, why not use the functionality to the fullest. I think this is a better link: https://blog.seidel-philipp.de/dshot-digital-esc-signal/

I would like to use flight controllers but I'm not using these escs for quadcopter usage. I can use PWM to interface with the flight controller (or are there other ways) but in that case I might as well connect directly to the escs.

In short, I ended up creating a library capable to drive multiple DShot600 ESCs:
DShot-Arduino
It still need a lot more polish, but the bit-banging works really well.

SPI method
I tried the method @dannyf mentioned, which involved combining 3 SPI bytes to form 1 dShot bit and it actually works.
But there's a few problem with SPI:

It takes up the valuable SPI port, in theory you can still connect other SPI devices, but;
maximum 1 dShot ESC can be connected
During transmission of the packet, the CPU need to wait for the whole task, assume we are sending DShot300, each packet is about 54us long so CPU is halt for that amount of time. If you are doing this in 1000Hz, that is 5% CPU time.
The timing is not very accurate to the DShot protocol standard

e.g. for DShot300, each bit is

1.25us High - 1.25us H/L - 0.83 Low
for a 16MHz Arduino, 1.25us will be 20 CPU cycles which is not accurate to transmit with a SPI byte

I end up with the following codes to send a bit:
inline void dshot_0(){
  SPDR = 0xFF;
  NOP;
  while (!(SPSR & _BV(SPIF))) ;
  SPDR = 0x60;
  NOP;
  while (!(SPSR & _BV(SPIF))) ;
  SPDR = 0x00;
  NOP8;
  while (!(SPSR & _BV(SPIF))) ;
}

inline void dshot_1(){
  SPDR = 0xFF;
  NOP;
  while (!(SPSR & _BV(SPIF))) ;
  SPDR = 0xFF;
  NOP;
  while (!(SPSR & _BV(SPIF))) ;
  SPDR = 0xF0;
  NOP8;
  while (!(SPSR & _BV(SPIF))) ;
}

Above code is for DShot150, the SPI was set to 4Mbps, to adhere to the correct timing, I cannot transmit a full DShot byte as all on or all off, here's how the calculation done:

4Mbit SPI, each bit 0.25us. Thus for 16M clock arduino:

DShot 0 sequence: 10 bits of 1, 14 bits of 0
DShot 1 sequence: 20 bits of 1, 4 bits of 0

Those NOPn are just macro for the number of NOPs. I avoided using SPI library code here since the overhead of making library call is quite a lot.
Pure software bit-banging
This is the method resulted in my library, since using hardware SPI won't give me any advantages of releasing CPU time, and doing some Math gives me that a DShot600 require total 27 CPU cycle on 16MHz UNO. Which the pattern is the following:

10 Cycle High -> 10 Cycle H/L (depending on bit 1/0) -> 7 cycles low

Which gives total of 1.6875us per bit or 27us per packet. To allow the very tight timing those are coded in assembly.
Also by applying bit-masking the library is capable of driving at most 8 ESCs on the same hardware port (on UNO, Digital pin 0-7, PORTD).
Update cycle
One last note about DShot is during my test, I found it is quite strict on the update frequency. It must be updated at exact time interval and I found the slowest update frequency will be around 500Hz. To provide the correct timing for that, the library used Timer 1 and by default update in 1000Hz frequency.

Have you try STM base Arduino and bidirectional D-Shot?
You library look great I will try it soon. Thank you for you participation.

for bi-directional, do you mean receiving D-shot signal using Arduino? If so, I believe it is impossible for these 8 bit CPUs.

Not sure why, but it does not work. My ESC beeps to tell me that there is a signal coming but the motor does not work. Any ideas on how to troubleshoot? I am really not confident that the interrupt works at this frequency. I use Arduino Nano which, by spec, should have 16MHz

@xandy indeed receiving the response of a Bidirectional DShot packet is very difficult for 8-bit AVRs! I recently got a prototype working.  It's a bit complicated but I tried to comment it well. Take a look!

you can make pwm follow a duty cycle.

single shot pwm would be difficult to do on an avr.
much better to use hardware spi. Looks like you can do use 3 spi bits for every dshot bit. So 6 bytes of spi transmission would enough for every dshot frame (16 dshot bits).
running hardware spi at 3*0.6Mhz = 1.8Mhz or where about on a 16MIPS avr would be quite doable.

Sounds promising! i want to connect 4 escs though, while the audrino only has 1 mosi. One idea is to use a demuxer. Any thoughts?

it will depend on how the esc firmware reacts to long periods of no (input) signal. if it requires the constant presence of an input signal, that wouldn't be a viable solution.

"pause between frames of at least 2 microseconds to indicate a frame reset" and "PID loop this pause is actually considerably longer"  . As mentioned here: https://blck.mn/2016/11/dshot-the-new-kid-on-the-block/. This might actually work!

How do I wire SPI, though? My ESC only has ONE data port... I cannot find information on that

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


text:
Arduino Interrupts Classes and Namespace
I'm working inside the Arduino IDE environment and have made a class that builds on the Adafruit RDG LCD with interrupts While looking at how to combine the Attach Interrupt() into my class I came across this post about using namespaces

Why make a class then? What about a namespace?
A class with one instance is like a group with one person in it.
-nickgammon

Understanding that Mr.Gammon is kind of a big deal around these parts, I'd like to understand how to insert/alter my current class into a namespace format. Currently, the most in-depth tutorial I've found is here, but I don't see how I would mix in the Attach Interrupt() function
Right now, my code looks like
/**** Pre-Setup *****/
#define Menu_PIN 3
voltile bool flag;

//Init Class
class LcdMenu : public Adafruit_RGBLCDShield
{
  public:
  MenuFoo()
}
LcdMenu LcdM;

//run Setup
void setup()   /****** SETUP: RUNS ONCE ******/
{
  pinMode(Menu_PIN, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(Menu_PIN), ProcMenu, FALLING);
}

void loop()
{
  if(flag){
    LcdM.MenuFoo();
    flag=false;
  }
}

//Handles Inturrupts for Class
void ProcMenu()
{
  flag=true;
}

//define MenuFoo
void LcdMenu::MenuFoo(){[code]}

As I understand it, Implementing a namespace would eliminate the need for the ProcMenu() function making my code easier to read/maintain.

You can move ProcMenu() into the LcdMenu class. It will have to be static and then you can write member function to hide the attachInterrupt() e.g. LcdM.begin(MENU_PIN);

why do you want to implement the screen menu in a class derived from a hardware wrapping class?

I'm trying to follow a principle of inheratence as I understand it the class LCD Menu is a Adafruit_RGBLCDShield As to why overall, I wanted a way to group the LCD functions together.

In this particular instance, and since you are inheriting from a class
of a known library, making your own class makes sense. You just have to
be aware that, although you can in principle have multiple instances of
a class, you can only have one single handler for a particular
interrupt. Thus the handler cannot be a regular method of the class (a
method that knows it has been called for this instance), but it can be
a static method. Such a method is much like a regular function which
uses (abuses?) the class as a sort of namespace.
I would try something along these lines:
class LcdMenu : public Adafruit_RGBLCDShield
{
public:
  LcdMenu();
  void begin([params]) {
    Adafruit_RGBLCDShield::begin([params]);
    attachInterrupt(digitalPinToInterrupt(Menu_PIN), handleInterrupt, FALLING);
  }
  void MenuFoo();
  void update() {
    if (flag) {
      MenuFoo();
      flag=false;
    }
  }
private:
  static volatile bool flag;
  static void handleInterrupt() { flag = true; }
}

volatile bool LcdMenu::flag;

Then you just have to call LcdM.update() in loop().

Don't forget to give your member functions return types... (apart from the constructor of course).

to clarify: begin() is the constructor and the member functions should read something to the effect of void MenuFoo();

Ok so I got the attachInterrupt() function into the class, but when I try to add static volatile bool flag; I get an error saying cckcVoVT.ltrans0.o:(.text.startup+0x838): undefined reference to 'LcdMenu::flag'

@Majenko: Oops! Fixed, thanks! @ATE-ENGE: LcdMenu::flag has to be defined, in addition to being declared. I added that to the code snippet in the answer.

I don't it will change your design.
The main reason to use namespaces is to have an extra 'layer' of hierarchy.
Like a book that can be divided in chapters (classes).
But if you want to combine multiple books (projects) than you use name classes (e.g. to prevent name clashes of equally named class names).


text:
Call class B from Class A
I have two classes in my sketch that are independent of each other (a serial output and an LCD display) A simplified structure of my code is as follows:
class A
{
  public:
   int x;
   void afoo()
   {
     x=1;
   }
   void afoo2
   {
     x=ClassB.bfoo+1;
   }
};

A ClassA;

class B
{
  public:
    int y;
    void bfoo()
    {
      y=ClassA.afoo+2;
    }
};
B ClassB;

However, if I don't comment out  class afoo2 I get the following error:

exit status 1
'ClassB' was not declared in this scope

I'm guessing that this is because I haven't yet created B ClassB while class is being defined. Is there a way I can do what I'm intending here?

You can't see non-static member variables in a class like that.  The closest is to make it static, which means you get one and only one copy of the variable across all instances of your class:
class ClassB;
class ClassA {
    public:
        int x;
        void foo();

};
class ClassB {
    public:
        static int bfoo;
};

void ClassA::foo() {
    x = ClassB::bfoo + 1;
}

However I suspect that isn't what you want. I suspect you actually want to see the bfoo value stored in class instance B - so you need to tell you classA instance A what and where B is. To do that you will have to pass it when constructing or during some other setup phase.  If you want A to know B and B to know A you can't easily do it during construction, so you will have to do it at a later stage:
class ClassB;

class ClassA {
    public:
        ClassB *B;
        int fooa;
        void begin(ClassB *b) {
            B = b;
        }
        void foo();
};
class ClassB {
    public:
        ClassA *A;
        int foob;
        void begin(ClassA *a) {
            A = a;
        }
        void foo();
};

void ClassA::foo() {
    fooa = B->foob + 1;
}

void ClassB::foo() {
    foob = A->fooa + 1;
}

ClassA A;
ClassB B;

void setup() {
    A.begin(&B);
    B.begin(&A);
}

void loop() {

}

Ok, why do you have class ClassB; and class ClassA A at the beginning as well as before the setup?

class ClassB; means "ClassB exists, but I am going to define it later on." It allows ClassA to know about the type ClassB even though ClassB hasn't been defined in the file yet.

trying your sketch, I'm getting an error forward declaration of 'class ClassB'

Actually, the foo() functions can't be contained within the class structure as I have it - they have to be external to it so that it knows the structure of the classes before they are used.  I will edit a working sketch in,

What you are trying to do is call class A from B and vice versa.
What you could try, is remove one of the functions out of the class, possibly to a third class, so class A and B depend on a class C and not on each other.
However, if they are really depend, you can split up the files in header/implementation files.
Instead of using two classes directly, pass them as a parameter (reference).
Somewhat like this (not tested)
File A.h:
class A
{
  public:
   int x;
   void afoo();
   void afoo2(B& b);
};

File A.cpp:
#include "A.h"
#include "B.h"

void A::afoo()
{
  x=1;
}

void A::afoo2(B& b)
{
  x=b.bfoo+1;
}

file B.h:
class B
{
  public:
    int y;
    void bfoo(A& a);
}

file B.cpp:
#include "A.h"
#include "B.h"

B::void bfoo(A& a)
{
  y=a.afoo+2;
}

And your ino file you declare A and B.
#include "A.h"
#include "B.h"

A ClassA;
B ClassB;

ClassA.afoo(ClassB);
ClassB.bfoo(ClassA);


text:
Echo from device not matching input
I'm writing a char array to a device with an arduino mega that should be giving me an echo back, instead, I'm getting an array back with different chars that correspond to my sent function, but not in a way I can figure out. for example {1,6,250,0,91,233,252} returns the array {127,62,1,146,90,0,0}
As 1 is always returning 127, I'm guessing it has something to to with how I'm casting my received data, but after messing with it for a few hours, I can't seem to get it to cast correctly.
Main Function
gets destination address and data, echos back if requested
calls CRC(this works fine) and SkRead(the problem area)
void Create_Message(int Address, int Data, bool echo)
{
  lcd.setCursor(0,1);
  lcd.print(Address);
  lcd.print(" ");
  lcd.print(Data);
  Address--;
  byte SvAdd = 1;
  byte FuCode = 6;
  byte AddHi = Address>>8;
  byte AddLo = Address;
  byte DatHi = Data>>8;
  byte DatLo = Data;
  byte AdDa[] = {SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo};
  uint16_t crc=CRC(AdDa,sizeof(AdDa)/sizeof(AdDa[0]));
  byte CrcHi = crc >> 8;
  byte CrcLo = crc & 0xFF;
  /*U8 Slave Address, U8, Function Code, U16 Address, U16 Data, U16 CRC
  * to
  *[U8 Address Split High, U8 Address Split Low, U8 Data Split High, U8 Data Split Low, U8 Function Code]
  */
  unsigned char cmd[8]={SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo,CrcLo,CrcHi};
  for (int i=0; i< 8; i++)
  {
  Serial1.write(cmd[i]);   // Send string
  if(echo){Serial.print(cmd[i]);Serial.print('.');}
  }
  if(echo){Serial.println();}
  if (SkRead(echo) == cmd)
  {
  Serial.print(Address);
  Serial.print('\t');
  Serial.println(Data);
  }
  //clear line
}

CRC
(works fine, just wanted to show full code)
/*---Create CRC Function---*/
uint16_t CRC(byte AdDa[], int Size )
{
  uint16_t crc16 = 0xFFFF;
  int pos = 0;
  int i = 0;
  /*Write CRC*/
  for (pos = 0; pos < Size; pos++)
  {
    crc16 ^= AdDa[pos];          // XOR byte into least sig. byte of crc
    for (i = 8; i!= 0; i--) // Loop over each bit
    {
      if ((crc16 & 0x0001) != 0)        // If the LSB is set
      {
        crc16 >>= 1;                      // Shift right and XOR 0xA001
        crc16 ^= 0xA001;
      }
      else
      {
        crc16 >>= 1;                      // Shift right
      }
    }
  }
  /*Note, this number has low and high bytes swapped,
  so use it accordingly (or swap bytes)*/
  return crc16;
}

SkRead
This is my problem area, I'm sure the data is being sent and read correctly, but one of my assignments is throwing it off so the received echo is not received in a way that matches what is sent.
unsigned char SkRead(bool echo)
{
  digitalWrite(Pin13LED, HIGH);  // Show activity
  outputstring = "";
  unsigned long bide=millis()+2000;
  byte inChar;
  while(Serial1.available()<8 && bide>millis()){}
  while(Serial1.available())
  {
    inChar = (byte)Serial1.read();
    outputstring += (char)inChar;
  }
  //Serial.println(outputstring);
  digitalWrite(Pin13LED, LOW);  // Show activity
  int charl = outputstring.length() + 1;
  unsigned char outputschar[charl];
  outputstring.toCharArray(outputschar,charl);
  if (echo)
  {
    for (int i=0; i< charl; i++)
    {
     Serial.print(outputschar[i]);
     Serial.print('.');
    }
    Serial.println();
  }
  return outputschar;
}

One thing I notice: You have CrcHi and CrcLo reversed in the array definition. Is it supposed to be?

Yes, low comes first.

I don't know where to start.

You did not provide a full sketch. There is, for example, no Serial.begin1() in sight.
You did not provide enough information about the device. If you don't want to tell us what it is, then give an indication of its age. In the 1980's it was common to have 7E1 format (7 data bits, even parity, 1 stop bit).
You have to be sure what the baudrate is. To detect a wrong baudrate, you need a oscilloscope or logic analyzer. When the device has a processor and the baudrate is derived from it's clock, the baudrate could be different from the specified baudrate by a few percentage. That is already a problem with the Arduino.
It could be a problem with inverse voltage levels. What does the device use as idle and as active level ? The Arduino Mega uses +5V at the TX pin when idle, and low is active. That means that the TX pin is normally high, and the first low pulse is the start bit.
The device could return an error code instead of an echo.
Your SkRead function can be improved:
Using a String object to collect the incoming data and after that converting the String object to a unsigned char array to use it, is not the most elegant solution. You could just use a unsigned char array to read the incoming data.
It is not okay to add something to the millis value. That is a problem when millis does a rollover (after 50 days or so).
Normally a character is read as soon as it is available. You wait until 8 characters are in a buffer. No one else does that.

To solve this puzzle you need more information. Try to capture the RX and TX signals with a oscilloscope or logic analyzer. Or else try to write a very small sketch that creates the problem.
My best guess is that it is not your sketch, but perhaps a combination of inverse levels, parity and baudrate.
[ADDED]
After writing down the bits over the serial bus, it might indeed be inverse voltage levels and maybe something with 7 bits or parity. That would also explain the last bytes to be 255. Those 255 are not valid data.


text:
how to prevent IR signal to go through 3d printed plastic?
I'm working on two arduino (one a dock, the other one on a robot) communicating through a IR to let the latter know about its location.
I 3D printed a piece which goal was to channel the 3 IR led lights, to prevent them from overlapsing (exactly in the same manner as the Kobuki.
For a reason I don't know, the IR signals seem to go through  the 3D printed piece which doesn't seem to let visible light through.
I known that there is no 100% absorbant materials, and I know "black for visible lights" doesn't necessarily mean "black for IR lights".
I think my problem is more related to my lack of experience in the field. My question is : why do I get signals from a IR led channeled toward a location I am not in ?
Patently, it means my light channels are not channeling light.
Therefore, better : How can I make a better (and cheap) channel for IR light ?
The piece I 3D printed is grey (silvery like I guess)
edit : to prevent incomprehension, i would like to clarify "channel". What I mean is to block all light "not going" in the right direction, whatever happens to that light. I apologize if it is not the word I should have used.

IR (infrared) is like heat, right? If you have a fire in your room, does it still get hot at the other end of the room, even if you have a chair between you and the fire?

We had this problem at a previous job - and it's surprisingly difficult. Long story short, we found that enclosing the devices inside cardboard boxes did NOT work, but wrapping the boxes entirely in aluminum foil, without a single gap, pretty much did work - although then it's difficult to get the cables in. Good luck.

Well one is first and foremost an electromagnetic radiation I can deflect with a mirror while the other is a mechanical energy of shock between molecules, isn't it ?

Oh, really ? I'm going to try and spread a little aluminum on the 3d printed thing, thank you

I use aluminium tape for this kind of thing. It's used for sealing joints in heat ducting. Cheap and easily obtainable, and being self adhesive makes it easy to apply.

Are you sure the signal isn't just reflecting of the walls.

didn't know it existed as tape as well, i'll look for that (I've stuck it with glue for now).

I don't think the signal is reflecting on walls, because I put a specific set up to try it !

You can also get reflective spray paint that is quite good. It's also used for EM shielding on the inside of plastic cases since it's conductive.

Are you using ASK modulation?  Are you using  ASK IR receiver devices commonly found in remotely controlled entertainment equipment?

It could still reflect of the 3D printed material. Try, and temporarily replace the IR leds with visible light leds, and see what you can still see.

You can not use common modulation remote control receivers as they contain an ACG feature which will likely "turn up the volume" until it detects even a weak reflected signal.  Instead consider if this reflective sensor, which does not contain an AGC feature, is appropriate for your design.
Alternatively you might explore the response time of the AGC feature to see if you can defeat its intended purpose.  That is to say, rapidly switch between IR transmitters in order to keep the AGC level at low gain.  Essentially blinding it from weak reflected signals.
You might also transmit continuously on all IR sources and determine if the AGC will put the weak signals below the noise floor.

I don't know if it will work but i've ordered some of these. Do you happen to know if they work with IRremote ( https://github.com/z3t0/Arduino-IRremote ) ?

We are supposed to avoid making recommendations.  However I could not find good technical information w/o referencing an actual part.

When working beyond tried and tested Arduino projects, you need to take the extra effort to verify if components will do what you expect.  In this case, most IR remote controls operate at about 38KHz.  There are exceptions.  Vishay makes several parts based on the linked to specifications.  According to this specification, the last 2 digits of the Vishay part number indicate the operating frequency.  At the bottom of page 1 two parts are listed in the parts table.  There the TSSP4038 is listed as operating at or near 38KHz.

I realize this is old but I have had a similar challenge making an code wheel for an optical encoder.  PLA material did not block the infrared.  however, all of the codewheels that I have made with black PETG material have worked.  Obviously you would want to fill in the shape as much as possible and assure that you do not have gaps between the layers.  Personally I have not had to make any tweaks with the Prusa MK3 printer, black PETG material and the common 0.2 layer height.

The best and cheapest way would be to use BLACK colored printing material as it would absorb the IR waves and would not let them pass!
I did a similar thing when I was building an IR-based Robot so using a black reflector and painting the chassis black increased the efficiency!
Black for visible light is the same for IR too as light is just a small spectrum of electromagnetic radiation, just as IR.

There are plenty of black materials that are completely transparent to IR.

The 3D printing material is generally not.


text:
Lines not pulsed fast enough (?))
Should this code pulse the PB3 and PB4 pins (MOSI and MISO of an Arduino Uno) at 2ms interval ?
#include <avr/io.h>

int main(void)
{

//  for (byte i = 0; i < 32; i++)
//    pinMode(i, INPUT);

  DDRB |= (1 << PB4);
  DDRB |= (1 << PB3);
//  pinMode(PB4, OUTPUT);
  while (1)
  {
    PORTB &= ~(1 << PB4);
    PORTB &= ~(1 << PB3);
  //  digitalWrite(PB4, LOW);
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//      __asm__ __volatile__("nop");
//    delayMicroseconds(10000);
    delay(1);
    PORTB |= (1 << PB4);
    PORTB |= (1 << PB3);
  //  digitalWrite(PB4, LOW);
//    delayMicroseconds(10000);
    delay(1);

  }
}

If used for SPI MOSI can do 1 MHz just fine - so my logic analyzer says. MISO would not behave when used by SPI. MISO works in other non-SPI scenario: I am able to use the Arduino for in-system programming other AVR boards.
But the code above pulses neither MISO nor MOSI, as pointed out by the same logic analyzer in the same setup. Should it?
update
There has been some issue with the board. Changed it and all works fine now, regardless of using int main() alone or also calling init() as per @Majenko 's answer

Code is looking ok. Are you sure that ports are not shorted by something, or driven from somewhere outside?

@smajli that was probably it. Feel free to turn the comment into an answer

The code content works fine while compiled as an Arduino program - that is, using the proper setup() and loop() structure:
void setup() {
    DDRB |= (1 << PB4);
    DDRB |= (1 << PB3);
    while (1) {
        PORTB &= ~(1 << PB4);
        PORTB &= ~(1 << PB3);
        delay(1);
        PORTB |= (1 << PB4);
        PORTB |= (1 << PB3);
        delay(1);
    }
}

void loop() {
}

However the same code will not work when using it in main(). This is simply because delay() will never work. Normally main() calls init() which then configures TIMER0 to generate the millis() and micros() count used for the delay() functions.
So either use setup() and loop() instead of main(), or make your program call init() before anything else:
int main() {

    init();

    DDRB |= (1 << PB4);
    DDRB |= (1 << PB3);
    while (1) {
        PORTB &= ~(1 << PB4);
        PORTB &= ~(1 << PB3);
        delay(1);
        PORTB |= (1 << PB4);
        PORTB |= (1 << PB3);
        delay(1);
    }
    return 0;
}

Makes sense. But, it didn't make a difference. Tried both calling init() and switching to setup().  As a sidenote, when I go lower with the delays, into tens / hundreds of microseconds, glithces start showing up on the MISO line. Going for even lower delays causes some (fewer) gltiches to also show up on MOSI .

Then your board is probably broken, or something, because that code does work. I tested it. It worked.

Yes... something like that. I wonder why the lines are doing fine when used as ISP at 19200 baudrate but not when pulsed at similar rates by hand. I am off to more investigations.

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


text:
Arduino board not recognized by Linux (dmesg, lsusb, etc.)
I just received my first Arduino board which is essentially a Leonardo (ATmega32U4) customized to include a NFC reader (PN532).
When I plug it in, the PWR LED comes on steady, the D13 LED flashes a few times, and then the STA LED blinks once and only the PWR LED is left on. I can upload a basic sketch to the correct Serial Port, but the Serial Monitor is always empty.
I have noticed that, when uploading the sketch, the RX/TX LEDs stay off (which I thought was a sign of uploading/downloading data). I figured this was the root of my issue so I tried to look into it further. Running lsusb does not find the device and dmesg does not show any information when (un)plugging the device.
I also tried on a Windows install, but couldn't install the Leonardo drivers since Device Manager wouldn't register any unknown USB/Arduino devices.
Do you think my board is dead on arrival or am I doing something wrong?

Update:
I just uploaded the Blink tutorial sketch and it uploaded "successfully" but I noticed no differences. Please note that I don't have an external LED attached, but am looking at the board's LED on pin 13. This pin already flashes a few times (as mentioned above) on a reset, so I modified the delay times and still noticed no change.

I am uploading using board Leonardo, as recommended for my hardware, and the serial port /dev/ttyS0. I thought this was the right port because I remember not seeing it at first, but on second thought I had a permission issue at first (which is now resolved) causing me to not see the port.
So it looks like my board is not detected by my computer and I'm successfully uploading sketches to a meaningless port. Any troubleshooting options for me? I've tried different USB ports and am, as of recently, plugging my board into external power (9V). The only thing I can think of that on my end is that I'm using a Y-cable for my USB connection (I have a normal Mini-USB coming tomorrow via Amazon) since it is all I had. I can also confirm that this USB connection does power the board when plugged in.

Something is inconsistent in your description - either the board is recognized, or else you cannot upload to it.

I'll say again, something is inconsistent in your report, as you cannot upload to a USB device which is not detected by the operating system.  There's something you aren't accurately reporting, and it is key to solving your issue.  Perhaps you are mistaken in thinking you managed to upload something?  To what serial device node did you allegedly upload?

Further to that, can you upload a demo such as 'blink' & have it flash an LED at you to confirm it's taken the upload?

@chrisStratton -- thanks for forcing me to look at this again, this is my first time really messing with hardware. Please see my update.

I'd like to ping @MarkWilliams also, since he pointed me to the Blink tutorial (which I thought I needed an external LED for).

/dev/ttyS0 is a serial port - not a serial-via-USB - and so will be looking for something plugged into a 9-pin D socket (or 25-pin; if you even have one at all) - this may well explain things, although there is meant to be 2-way comms. I'd definitely check the cable as Arduino boards lighting up & flashing is a good sign! Do you not have a printer cable or something you can 'borrow'?

I have a camera card at my girlfriend's that is Mini-USB, but none in the office here (surprisingly). I'll just wait until tomorrow and get back to you guys unless there are any other ideas. Glad I was on the right track buying a cord to troubleshoot :)

Just to confirm, would I be looking for a /dev/ttyUSB0 or /dev/ttyACM0 instead of /dev/ttyS0? Either way, I believe it should show up in my kernel log if I have a good connection..

A Y cable should work (if it still works on its original disk drive) if you plug in the end that actually has data wires.

@ChrisStratton it's not a normal split Y-cable, the other end is a female USB-A (see image)..didn't know what else to call it

@MarkWilliams -- it was the USB cable only sending power, not data. Either of you can submit an answer for points (thanks for the help)..if not, I'll write my own answer later.

So, to summarise the comments trail; the blinking lights at power-up are the normal boot sequence for the Leonardo,  indicating the processor is good, and that power is reaching the board; the device seen should be /dev/ttyACM0 or some other number; dmesg wasn't recording a plug-in event as the cable was not good.
We still don't quite know why the IDE thought it had sent a program to /dev/ttyS0, but presumably the level of interaction is much less (ie, none) via RS232 serial? Which explains why it said it had uploaded a test program when, in fact, it hadn't!
And replacing the USB cable has solved the problem - excellent news!


text:
Can I program AVR Microcontrollers using Arduino Development board with AVR Studio?
I know and I can program any AVR microcontroller with Arduino IDE and Arduino Uno board. Can I use Arduino board with AVR Studio? Or I have to buy an AVR Development board?

You can use Atmel Studio to write code for the MCU(s) on the Arduino boards. If the IDE itself does not support uploading the code to the Arduino then it is still possible to use AVRDUDE or BOSSA to upload it via the command line.

Using Atmel Studio, could he program via ISP (SPI)? I have never tried it as I have a Dragon and STK500.

I'm sure he could. But the Arduino likely already has a perfectly good bootloader on it for serial uploading.

@IgnacioVazquez-Abrams Then what happens If wanted to upload code from Atmel Studio while Arduino has it's own bootloader loaded on the MCU? Does that matter?

@Zgrkpnr__: All the Arduino bootloader does is allow serial programming instead of requiring ISP. It does not affect the development environment in any other way.

@IgnacioVazquez-Abrams You are giving answers as If you read my mind.

There is an Arduino plugin available for AVR Studio, which allows you to upload sketches to an Arduino, just like you would with the Arduino IDE. I think this also enables you to upload plain C/C++ files created with the standard AVR tools.
Alternatively, if you have an AVR ISP programmer, you can use this to upload compiled C/C++ to the Arduino from AVR studio without needing the Arduino plugin.


text:
Can an AT89S52 be programmed using an Arduino as ISP?
Since the AT89S52 controller is ISP programmable is it possible to use an Arduino UNO as a programmer to upload the hex file to the 8952 ?
I've tried various programmer softwares such as progisp, 8051 loader and ISP Prog v1.4 but the Arduino doesnt show up as a programmer on any of these. I've uploaded the ArduinoISP sketch on the UNO and then tried to program the 8952 without any luck.
According to my understanding the ISP programmers use an ATMega8 ,so is what I'm trying to do possible or do I need to purchace an ISP programmer ?

Have you placed a capacitor between ground and reset?

Yup, I've tried putting a 10uF cap between the reset an ground of the arduino.

You might be able to use the programmer sketch I wrote a while back (it runs on a Uno). You need an SD card interface so it can read the .hex file for programming. See: http://www.gammon.com.au/uploader
You connect things up roughly like this (Atmega328P shown, your wiring would be different at the target chip side):

You would need to modify the sketch to add the details for the AT89S52. As far as I can make out from the datasheet:

Signature: 0x1E 0x52 0x06
PROGMEM: 8k bytes
RAM: 256 bytes
Pinouts: Depending on the chip package. You need to identify MOSI/MISO/SCK/RESET along with Vcc and Gnd.
Fuses: None that I can see
Flash page size: 256 bytes

Thus you could modify the table of chips to add that one, along these lines:
// see Atmega datasheets
const signatureType signatures [] PROGMEM =
  {
//     signature        description   flash size   bootloader  flash  fuse
//                                                     size    page    to
//                                                             size   change

  // AT89S52
  { { 0x1E, 0x52, 0x06 }, "AT89S52",   8 * kb,           0,   256,   NO_FUSE },

// ... other ones here ...

I haven't got an AT89S52 to test it on, so I can't say for sure I got those parameters right. I am assuming that the programming instructions for ICSP programming are the same as for the other chips in their range.

Sketch source: https://github.com/nickgammon/arduino_sketches

Thank you so much for this brilliant guide! I shall test this today and get back to you with the results!

You should be able to use the Arduino as an ISP since an ISP is basically just a serial to SPI interface. If you are trying to use the arduino software to upload your program, you will need to edit your boards.txt file to be able to talk to the chip. If you are just using avrdude you will need to update your avrdude.conf.  AVR Freaks has a post on someone trying something similar and may be of some help. Without knowing your environment it's difficult to give more specific advice

I've used keil to get the hex file of  a simple blink program written in C. The problem I'm facing is burning this hex file onto the AT89S52. I've tried using progisp, 8051 loader and ISP Prog v1.4 but none of them detect the Uno as a programmer. Also I've uploaded the ArduinoISP sketch onto the Arduino.

You provided information for a) Arduino IDE and b) Avrdude. While accurate and correct, I am looking for a way to use programs like AVRISP, or PROGISP to work with Arduino as ISP. Because they provide easy and graphical interface to a) read HEX and b) program using ISP. Is there any way to use an Arduino Uno programmed with ISP sketch with these software? Sorry for the long comment.

If you haven't been successful yet, Try this.(assuming it's still not solved.)
I'm using Arduino to successfully program the AT89S52.
Need 2 tools:
Arduino program and
an AT89S52 programmer software.
Here's a complete tutorial on how to do it.
Works on Windows, not so sure about linux.
http://www.instructables.com/id/ARDUINO-AS-A-8051-PROGRAMMER/?ALLSTEPS

authors: Александр Кирьянов


text:
ATMega328 not able to fully switch coreless motor on
I'm having trouble regarding motor control in a project I'm working on.
It uses an ATMega328 DIP package on a PCB. The motors I'm using are small coreless motors and I'm trying to control them using Si2302ds N-MOS FETs. For the power supply I'm using a 3.7V(4.2V on full charge) Lipo. I've tested this setup with a promini before and the motors turned on and off just fine.
This time I'm having problems with controlling 1 motor out of the 4. I've attached 0.1uF caps across each motor terminal (see schematic). Them control pins used for the motors are pins 3,5,6,9. The problem occurs at pin 3. I tried running the blink program on pin 3 to pulse the motor on and off through the FET but all I get is a bit of clicking from the motor.
Things I've already checked relating to the circuit :

FETs are soldered on correctly and made sure they aren't defective.
Motor works fine prior to connecting it to the circuit.
Disconnected the FET and motor from pin 3 and checked the output.
It works fine on its own.

The puzzling thing is that only 1 motor (at pin 3) seems to struggle to come on. The rest work just fine. Also if I try and turn all 4 motors ON, it doesn't work. But if I turn only the 3 working ones on and keep the non-working one off they turn on perfectly.
Is the problem occuring due to noise generated by the motor? What could be the problem? I've attached the schematic to this post below.

Can you interchange any pins / FETs / motors?  Eg, exchange the pin 3 and 5 connections to see if another pin drives 3's FET ok, or if 3 can drive another FET ok, and similarly for motors.

Indeed, mix and match would be a good idea.  If you mean "pager" type moters they can fail in interesting ways resulting in very high current drain.  Also use a scope, or failing that a speaker with DC blocking cap to make sure the pin in question is constantly on - perhaps try a simpler program that does nothing but drive that pin and enter an infinite loop.

What's your clock speed?

jwpat7 I have tried driving that motor with Pin 7 but without any luck. Though that is only a digital pin and without PWM capability.

canadiancyborg I'm using a 16MHz crystal

Can you post a higher resolution schematic? That is almost unreadable.

"I have tried driving that motor with Pin 7": Using 7 introduces another variable. What would be more useful is to interchange the motor on pin3 with one from 5, 6, or 9 - the working combinations. Then see if the problem follows the motor or the pin.

Nick Gammon Sorry for that, I've updated the post with a clear picture of the motor control circuit.

@JRobert and Chris - I removed the chip form the PCB, then put it into the Arduino board and ported the o/ps to the chip socket in the PCB. The circuit functioned fine in this setup but failed again after putting the chip into the PCB. So is it some sort of under-powering issue with the ATMega328 ? I'm using a 3.7V 500mAh  25C lipo. This supply worked well when I tested this setup on a breadboard. My understanding is that the ATMega328 brown out is set at 2.7V so the chip also should've been able to function.

A couple of thoughts: 1) The issue only happens with the chip on the PCB so the PCB environment is suspect. The PCB itself was used in both trials, right? If so, its hdw is prob OK. 2) On the Arduino, did you power with 5V? From USB? Then the PCB/LiPo combo might be starved for power. 2) Pin 3 is the only one of the 4 using Timer-2 for PWM. That might mean that in that chip, T-2 is closest to its margins, so is the first one to fail. Try testing the LiPo voltage for droop under load. 4) Try pin-10 instead of pin-3; it uses Timer-1. Definitely not a fix :)  but it might be instructive.

@JRobert No luck on pin 10 either! Yes the PCB was used in both cases. I'm not sure if it is a power issue anymore since even when I'm switching that single motor on it does not seem to work. I tried swapping chips but the problem still persists. When I cut the trace to the non-working pin, the other 3 motors work fine and even the unconnected pin3 works fine when I checked it with a DMM.

@SidharthM - let's take this to chat: http://chat.stackexchange.com/rooms/info/47641/atmega328-not-able-to-fully-switch-coreless-motor-on?tab=general

authors: พัชรีญา จันทร


text:
Pinball - "All Lanes Lit" Bonus score is not behaving as expected
I'm trying to build a (very basic) pinball machine with an Arduino Uno. This part of the code will detect when a ball passes 3 lanes. When a lane is passed, it will activate the lane(laneState), reward a score(+10) and light up an LED.
The Expected Result:

When all 3 lanes are LIT, assign a score of the lane passage(+10), assign a bonus score(+100) and reset all laneStates to 0 and turn all leds to LOW.
110 points are being added in total

Actual Result:

the last lane passed lights back up as active (while I set all of them to inactive)
120 points are being added in total (instead of 110?)

Any hints on why I see this behaviour are very welcome!

The sketch and board can be found here: https://circuits.io/circuits/2739062-poc-lane-passage-001/
Turn on 'Code Editor' and enable the Serial Monitor to see the scores.

More info:
I looked into using interrupts, but that is not an option here (the Uno only has 2 pins for interrupts, I need 3)
Thanks!
EDIT: added the code here too:
// Scores
int totalScore = 0;
const int lanePassageScore = 10; // 10 points for passing a lane
const int allLaneActiveBonus = 100; // 100 points for activating ALL lanes

// Digital pins to detect the state of the buttons
const int laneButtonPin[] = {2,3,4};
const int laneStateLedPin[] = {10,11,12};

// all three lanes are 'inactive' at the start of the game
int laneButtonState[] = {0,0,0};
int lastLaneButtonState[] = {0,0,0};
int laneState[] = {0,0,0};

void setup() {
  Serial.begin(9600); // for debugging
}

void loop() {
  // detect if lanes 1 to 3 were activated
  detectLaneButtonPassage(0); // Lane 1
  checkAllLanesLit();
  detectLaneButtonPassage(1); // Lane 2
  checkAllLanesLit();
  detectLaneButtonPassage(2); // Lane 3
  checkAllLanesLit();

  Serial.println(totalScore); // for debugging

  delay(5);
}

void detectLaneButtonPassage(int laneId){
  // Check state of the button
  laneButtonState[laneId] = digitalRead(laneButtonPin[laneId]);
  if(laneButtonState[laneId] != lastLaneButtonState[laneId]){
    if(laneButtonState[laneId] == HIGH){
      // The lane button change to an ON position, toggle the lane state
      if(laneState[laneId] == 0){
        // lane was not yet active, it becomes active now
        laneState[laneId] = 1;
        digitalWrite(laneStateLedPin[laneId], HIGH);
        rewardScore(lanePassageScore);
      }else{
        // lane was already active, it becomes inactive now
        laneState[laneId] = 0;
        digitalWrite(laneStateLedPin[laneId], LOW);
        rewardScore(lanePassageScore/2);
      }
    }
  }
  lastLaneButtonState[laneId] = laneButtonState[laneId];
}

void rewardScore(int score){
  totalScore += score;
}

void checkAllLanesLit(){
  // Check if ALL lanes are activated
  if(laneState[0]==1 && laneState[1]==1 && laneState[2]==1){
    // reset all buttons and states
    for(int laneId=0; laneId<=2; laneId++){
      laneButtonState[laneId] = 0;
      lastLaneButtonState[laneId] = 0;
      laneState[laneId] = 0;
      digitalWrite(laneStateLedPin[laneId], LOW); //Turn off led
    }
    rewardScore(allLaneActiveBonus);
  }
}

There are 2 lines of code that need to be removed from the checkAllLanesLit() function in order for your code to work as desired:
  laneButtonState[laneId] = 0;
  lastLaneButtonState[laneId] = 0;

Explanation:
What is happening is that the detectLaneButtonPassage() is firing as normal. Then checkAllLanesLit() runs and clears the lastLaneButtonState flag.
The program loops around again and the lane button is still pressed. However, the detectLaneButtonPassage() fires again because lastLaneButtonState has been reset and it appears to the program as a rising edge. Hence the extra 10 points.

On a side note, the following 2 lines could be reduced down to a single line:
if(laneButtonState[laneId] != lastLaneButtonState[laneId]){
    if(laneButtonState[laneId] == HIGH){

The above lines of code are detecting a rising edge. They can be expressed as:
if(laneButtonState[laneId] && !lastLaneButtonState[laneId]){

For the if statement to fire laneButtonState must be high and lastLaneButtonState must be low.

I'll try this asap. Thanks for your time already.

Works perfect!  Now it makes sense to not have those lines there. I'm also not that experienced/efficient yet with condensing 2 lines of code in one. But i'll definitely keept this in mind for later! Thx again!

Looks like a timing issue.
Which ever order you hit the buttons in the last one always stays lit (and you get an extra 10 points added).
I set a breakpoint at:
rewardScore(allLaneActiveBonus);

...and just waited a sec and then continued and your code worked as expected.
So I think that you are setting all lines to LOW in checkAllLanesLit() and then only have a short delay (5mS) before looping round and checking again (at which point the button is still HIGH as you haven't taken your finger off it quickly enough) - resulting in the additional 10 points and that lane being lit again.

authors: Усердный бобёр


text:
esp8266 not defined in scope while using in class
Below code was working fine without using classes, after using class an error pops up: esp8266 is not defined in this scope
#include<SoftwareSerial.h>
#include<ArduinoJson.h>
#include<Wire.h>
#include<LCD.h>
#include<LiquidCrystal_I2C.h>
#include<SPI.h>

#define DEBUG true
// Housekeeping stuff for LCD display
#define I2C_ADDR    0x3F
#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
LiquidCrystal_I2C
lcd(I2C_ADDR, En_pin, Rw_pin, Rs_pin, D4_pin, D5_pin, D6_pin, D7_pin);

class baseFunctions {
  public:
    baseFunctions() {
      Serial.begin(115200); // Housekeeping stuff
      esp8266.begin(115200);  // Housekeeping stuff
      sendData("AT+RST\r\n", 2000, DEBUG); // reset module

      // Code for display
      lcd.begin (16, 2);
      lcd.setBacklightPin(BACKLIGHT_PIN, POSITIVE);
      lcd.setBacklight(HIGH); // Switch on the backlight
      lcd.home (); // go home
      lcd.print("In development");

      pinMode(8, OUTPUT);
    }

    String sendData(String command, const int timeout, boolean debug) {
      String response = "";
      esp8266.print(command); // send the read characte to esp8266
      long int time = millis();
      while ( (time + timeout) > millis() ) {
        while (esp8266.available()) {
          // The esp has data so display its output to serial window
          char c = esp8266.read(); // read the next character
          response += c;
        }
      }
      if (debug) {
        Serial.print(response);
      }
      return response;
    }

    void connectToWifi() {
      sendData("AT+CWMODE=1\r\n", 3000, DEBUG); // Configure as clint
      sendData("AT+CWJAP=\"moto g\", \"hvats555\"\r\n", 5000, DEBUG);  // Connects to wifi
    }

    String fetchJson() {
      StaticJsonBuffer<200> jsonBuffer;
      char json[] = "{\"power\":\"high\"}";
      JsonObject& root = jsonBuffer.parseObject(json);

      const char* power = root["power"];
      return power;
    }
};

void setup() {
  baseFunctions go;
}

void loop() {
}

Here is the error
exit status 1
'esp8266' was not declared in this scope

It's right, you know. esp8266 has not been declared. Maybe you should declare it?

code is working fine without using class

Oh I apologise.

If it was working before you added the class (with esp8266 in it) then you must have deleted the code that declares esp8266 - because it sure isn't there now.

@LookAlterno I disagree. Helping people to learn how to code their Arduinos is within our remit - and if that means solving the odd compilation problem then so be it

@LookAlterno Probably better to have that discussion in meta than in comments.

When you added the class you obviously deleted/moved code into it from elsewhere.
One bit of code that you missed in that moving around will be the code that declares what esp8266 is:
SoftwareSerial esp8266(2,3); // for example

Find that in your original code and copy it across.