树老大 发表于 2024-10-22 01:54:40

arduino测试代码

#define TdsSensorPin A1
#define VREF 5.0      // analog reference voltage(Volt) of the ADC
#define SCOUNT30         // sum of sample point
int analogBuffer;    // store the analog value in the array, read from ADC
int analogBufferTemp;
int analogBufferIndex = 0,copyIndex = 0;
float averageVoltage = 0,tdsValue = 0,temperature = 25;

void setup()
{
    Serial.begin(115200);
    pinMode(TdsSensorPin,INPUT);
}

void loop()
{
   static unsigned long analogSampleTimepoint = millis();
   if(millis()-analogSampleTimepoint > 40U)   //every 40 milliseconds,read the analog value from the ADC
   {
   analogSampleTimepoint = millis();
   analogBuffer = analogRead(TdsSensorPin);    //read the analog value and store into the buffer
   analogBufferIndex++;
   if(analogBufferIndex == SCOUNT)
         analogBufferIndex = 0;
   }   
   static unsigned long printTimepoint = millis();
   if(millis()-printTimepoint > 800U)
   {
      printTimepoint = millis();
      for(copyIndex=0;copyIndex<SCOUNT;copyIndex++)
      analogBufferTemp= analogBuffer;
      averageVoltage = getMedianNum(analogBufferTemp,SCOUNT) * (float)VREF / 1024.0; // read the analog value more stable by the median filtering algorithm, and convert to voltage value
      float compensationCoefficient=1.0+0.02*(temperature-25.0);    //temperature compensation formula: fFinalResult(25^C) = fFinalResult(current)/(1.0+0.02*(fTP-25.0));
      float compensationVolatge=averageVoltage/compensationCoefficient;//temperature compensation
      tdsValue=(133.42*compensationVolatge*compensationVolatge*compensationVolatge - 255.86*compensationVolatge*compensationVolatge + 857.39*compensationVolatge)*0.5; //convert voltage value to tds value
      //Serial.print("voltage:");
      //Serial.print(averageVoltage,2);
      //Serial.print("V   ");
      Serial.print("TDS Value:");
      Serial.print(tdsValue,0);
      Serial.println("ppm");
   }
}
int getMedianNum(int bArray[], int iFilterLen)
{
      int bTab;
      for (byte i = 0; i<iFilterLen; i++)
    bTab = bArray;
      int i, j, bTemp;
      for (j = 0; j < iFilterLen - 1; j++)
      {
    for (i = 0; i < iFilterLen - j - 1; i++)
          {
      if (bTab > bTab)
            {
    bTemp = bTab;
          bTab = bTab;
    bTab = bTemp;
       }
    }
      }
      if ((iFilterLen & 1) > 0)
bTemp = bTab[(iFilterLen - 1) / 2];
      else
bTemp = (bTab + bTab) / 2;
      return bTemp;
}


页: [1]
查看完整版本: arduino测试代码