|
最近个人在做一个简单的小项目,如题,项目里用到的是UNO,tds与ph两种传感器,以及LCD1602实时显示数据,传感器具体样式如下淘宝链接
[size=13.3333px]https://item.taobao.com/item.htm?id=632462484025
[size=13.3333px]https://item.taobao.com/item.htm?id=608203826244
从github上自己找的各部分零件代码拼接起来。ph代码运行没什么问题,但是tds部分的代码存在数据更新延迟大,tds显示位数异常等问题
代码如下:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
#define SensorPin 1 // the pH meter Analog output is connected with the Arduino’s Analog
unsigned long int avgValue; //Store the average value of the sensor feedback
float b;
int buf[10],temp;
#define TdsSensorPin A0
#define VREF 5.0
#define SCOUNT 30
int analogBuffer[SCOUNT];
int analogBufferTemp[SCOUNT];
int analogBufferIndex = 0,copyIndex = 0;
float averageVoltage = 0,tdsValue = 0,temperature = 25;
void setup()
{
Serial.begin(9600);
lcd.init();
lcd.begin(16, 2);
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print(" Welcome to ");
lcd.setCursor(0, 1);
lcd.print(" WaterTect ");
delay(2000);
lcd.clear();
pinMode(TdsSensorPin,INPUT);
}
void loop()
{
//TDS parameter
static unsigned long analogSampleTimepoint = millis();
if(millis()-analogSampleTimepoint > 40U)
{
analogSampleTimepoint = millis();
analogBuffer[analogBufferIndex] = analogRead(TdsSensorPin);
analogBufferIndex++;
if(analogBufferIndex == SCOUNT)
analogBufferIndex = 0;
}
static unsigned long printTimepoint = millis();
if(millis()-printTimepoint > 800U)
{
printTimepoint = millis();
for(copyIndex=0;copyIndex<SCOUNT;copyIndex++)
analogBufferTemp[copyIndex]= analogBuffer[copyIndex];
averageVoltage = getMedianNum(analogBufferTemp,SCOUNT) * (float)VREF / 1024.0;
float compensationCoefficient=1.0+0.02*(temperature-25.0);
float compensationVolatge=averageVoltage/compensationCoefficient;
tdsValue=(133.42*compensationVolatge*compensationVolatge*compensationVolatge - 255.86*compensationVolatge*compensationVolatge + 857.39*compensationVolatge)*0.5;
Serial.print("TDS Value:");
Serial.print(tdsValue,0);
Serial.println("ppm");
//pH parameter
for(int i=0;i<10;i++)
{
buf=analogRead(SensorPin);
delay(10);
}
for(int i=0;i<9;i++)
{
for(int j=i+1;j<10;j++)
{
if(buf>buf[j])
{
temp=buf;
buf=buf[j];
buf[j]=temp;
}
}
}
avgValue=0;
for(int i=2;i<8;i++)
avgValue+=buf;
float phValue=(float)avgValue*5.0/1024/6;
phValue=3.5*phValue;
lcd.setCursor(0, 0);
lcd.print("TDS : ");
lcd.print(tdsValue,0);
lcd.setCursor(0, 1);
lcd.print("pH Val:");
lcd.setCursor(8, 1);
lcd.print(phValue);
delay(2000);
}
}
int getMedianNum(int bArray[], int iFilterLen)
{
int bTab[iFilterLen];
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[i + 1])
{
bTemp = bTab;
bTab = bTab[i + 1];
bTab[i + 1] = bTemp;
}
}
}
if ((iFilterLen & 1) > 0)
bTemp = bTab[(iFilterLen - 1) / 2];
else
bTemp = (bTab[iFilterLen / 2] + bTab[iFilterLen / 2 - 1]) / 2;
return bTemp;
}
数据刷新延迟如图
同时液晶显示的第一行在取出传感器后本应显示“TDS: 0“,但是实际显示的却是”TDS: 048“,原本的148清零后后两位数保留下来了
求助各路大神指正代码当中的问题与更改意见
|
-
|