Advertisement
KRITSADA

PID Example Reading analog input control Motor from VR

Aug 10th, 2016
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.90 KB | None | 0 0
  1. /********************************************************
  2.  * PID Basic Example
  3.  * Reading analog input 0 to control analog PWM output 3
  4.  ********************************************************/
  5.  
  6. #include <PID_v1.h>
  7. #include <ModbusRtu.h>
  8.  
  9. #define PIN_INPUT 1
  10. #define PIN_OUTPUT 3
  11. #define E2 3
  12. #define I3 3
  13. #define I4 13
  14.  
  15. // data array for modbus network sharing
  16. uint16_t au16data[16];
  17.  
  18. //Define Variables we'll be connecting to
  19. double Setpoint, Input, Output;
  20.  
  21. //Specify the links and initial tuning parameters
  22. //double Kp=1.0, Ki=0.5, Kd=1.0;
  23. double Kp=1.4,Ki=0, Kd=0;
  24. //double Kp=1, Ki=0.18, Kd=0;
  25.  
  26. PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);
  27. Modbus slave(1,1,0); // this is slave @1 and RS-232 or USB-FTDI
  28.  
  29. void setup()
  30. {
  31.  
  32.   //initialize the variables we're linked to
  33.   Setpoint = analogRead(A4);
  34.   Input = analogRead(A5);
  35.  
  36.   pinMode(E2,OUTPUT);
  37.   pinMode(I3,OUTPUT);
  38.   pinMode(I4,OUTPUT);
  39.  
  40.   //turn the PID on
  41.   myPID.SetMode(AUTOMATIC);
  42.   myPID.SetSampleTime(50); //200ms
  43.   myPID.SetOutputLimits(0, 255);
  44.  
  45.   Serial.begin(9600);
  46.   slave.begin( 19200 ); // baud-rate at 19200
  47. }
  48.  
  49. void loop()
  50. {
  51.  Setpoint = analogRead(A4);
  52.   Input = analogRead(A5);
  53.   myPID.Compute();
  54.  
  55.   digitalWrite(I3,HIGH);
  56.   digitalWrite(I4,LOW);
  57.   analogWrite(PIN_OUTPUT, Output);
  58.  
  59.  Serial.print("\n");
  60.  Serial.print(Setpoint);
  61.  Serial.print("\t");
  62.  Serial.print(Input);
  63.  //Serial.print("\t");
  64.  //Serial.print( Output);
  65.  Serial.print("\t");
  66.  Serial.print( 700);
  67.   Serial.print("\t");
  68.  Serial.print( 300);
  69.  
  70.  au16data[1]= Input;
  71.  au16data[2]= Setpoint-Input;
  72.  //Setpoint = au16data[3];
  73.  Kp = au16data[4];
  74.  Ki = au16data[5];
  75.  Kd = au16data[6];
  76.  myPID.SetMode(AUTOMATIC);
  77.  
  78.  au16data[7]= Kp;//myPID.GetKp();
  79.  au16data[8]= Ki;//myPID.GetKi();
  80.  au16data[9]= Kd;//myPID.GetKd();
  81.  
  82.  PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);
  83.  slave.poll( au16data, 16 );
  84.  
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement