วันพุธที่ 4 ธันวาคม พ.ศ. 2556

Arduino + PID + RelayOutput +DHT11

/********************************************************
 * PID RelayOutput Example
 * Same as basic example, except that this time, the output
 * is going to a digital pin which (we presume) is controlling
 * a relay.  the pid is designed to Output an analog value,
 * but the relay can only be On/Off.
 *
 *   to connect them together we use "time proportioning
 * control"  it's essentially a really slow version of PWM.
 * first we decide on a window size (5000mS say.) we then
 * set the pid to adjust its output between 0 and that window
 * size.  lastly, we add some logic that translates the PID
 * output into "Relay On Time" with the remainder of the
 * window being "Relay Off Time"
 ********************************************************/



#include <PID_v1.h>
#include <dht11.h>
dht11 DHT11;
#define DHT11PIN 2
#define RelayPin 6

//Define Variables we'll be connecting to
double Setpoint, Input, Output;

//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint,40,50,1, DIRECT);

int WindowSize = 5000;
unsigned long windowStartTime;
void setup()
{
  Serial.begin (9600);
  windowStartTime = millis();

  //initialize the variables we're linked to
  Setpoint = 45;

  //tell the PID to range between 0 and the full window size
  myPID.SetOutputLimits(0, WindowSize);

  //turn the PID on
  myPID.SetMode(AUTOMATIC);
}

void loop()
{

  int chk = DHT11.read(DHT11PIN);
  float ftemp= (float)DHT11.temperature;
  // delay(500);
    switch (chk)
  {
    case 0: Serial.println(Setpoint);Input = (double)ftemp;break;
    case -1: Serial.println("Checksum error"); break;
    case -2: Serial.println("Time out error"); break;
    default: Serial.println("Unknown error"); break;
  }

  //Input = analogRead(0);
  delay(500);// Delay for DHT11 read temperature.
  myPID.Compute();

  /************************************************
   * turn the output pin on/off based on pid output
   ************************************************/
  if(millis() - windowStartTime>WindowSize)
  { //time to shift the Relay Window
    windowStartTime += WindowSize;
  }
  if(Output < millis() - windowStartTime)
  {digitalWrite(RelayPin,LOW);
  Serial.print("LOW-");}
  else
  {digitalWrite(RelayPin,HIGH);
  Serial.print("HIGH-");}

  Serial.print(Input);
  Serial.print("-");
  Serial.print(Output);
  Serial.print("-");
  Serial.print(millis());
  Serial.print("-");
  Serial.println(windowStartTime);

}


ไม่มีความคิดเห็น:

แสดงความคิดเห็น