<--Blog#4

Blog#6-->>

 

***************CODE***************

 

 

 

#include <Arduino_LSM6DS3.h>
#include <SAMD21turboPWM.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <SPI.h>
#include <WiFiNINA.h>
#include <avr/dtostrf.h>


#define ONE_WIRE_BUS 21//temp
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
#define DEVICE_LABEL "arduino-nano-33"
#define TOKEN "BBFF-wKTuRwsXszVQuGUMJvEUcQIuz0xNtq"




char const * VARIABLE_LABEL_2 = "seti";
char const * VARIABLE_LABEL_3 = "T_di";
char const * VARIABLE_LABEL_9 = "seto";
char const * VARIABLE_LABEL_10 = "T_ana";
char const * VARIABLE_LABEL_16 = "x";
char const * VARIABLE_LABEL_17 = "y";
char const * VARIABLE_LABEL_18 = "z";
char const * VARIABLE_LABEL_19 = "gx";
char const * VARIABLE_LABEL_20 = "gy";
char const * VARIABLE_LABEL_21 = "gz";




char const *SERVER="things.ubidots.com";
//Replace the above line if you are an Educational user char const *SERVER="things.ubidots.com";


const int HTTPPORT= 443;
char const *AGENT="Arduino Nano 33 IoT";
char const *HTTP_VERSION = " HTTP/1.1\r\n";
char const *VERSION ="1.0";
char const *PATH= "/api/v1.6/devices/";


char const * SSID_NAME = "Sid"; // Put here your SSID name
char const * SSID_PASS = "9639554688sid"; // Put here your password


int status = WL_IDLE_STATUS;


//Pins
int PWM_pin = 5;//TEC PWM    timer0
int PWMF_pin=8;//FAN PWM   timer2


//l298n_tec
#define in1 4
#define in2 6
//FAN
#define in3 7//change
#define in4 9//change


/*-------------------------------------------------*/
//Variables for TEC
//float tempdigi;
//Start temp digi
float Init_temp=32;
float tempdigi;
float set_temperature = 15;
float PID_error = 0;
float previous_error = 0;
float  elapsedTime, Time, timePrev;
int  PID_value = 0;
#define pwm_factor 1
int pwmtec;


//Variables for FAN
//Start temp digi
float temp_analog;
float setF_temperature = 32 ;//room temp if rise activate PID_FAN
float  PIDF_error = 0;
float  previousF_error = 0;
float  elapsedTimeF, TimeF, timePrevF;
int  PIDF_value = 0;
#define pwmF_factor 231
int pwmfan;


TurboPWM pwmF;
TurboPWM pwmT;
//PID constants for TEC
  float  kp =950/*120 0.4*/; float ki =0.01 /*0.05*/;  float kd = 0;
int PID_p = 0;  float PID_i = 0;  int PID_d = 0;


//PID constants for FAN
float  Fkp = 300/*235*/; float Fki =1;  float Fkd =0;
int PIDF_p = 0;  float PIDF_i = 0;   int PIDF_d = 0;


//analog type thermistor
int Vo;
float R1 = 10000; // value of R1 on board
float logR2, R2;
float c1 = 0.001129148, c2 = 0.000234125, c3 = 0.0000000876741; //steinhart-hart coeficients for thermistor


//---- 4 acc & gyrpo--------------


float x, y, z,gx, gy, gz;




WiFiSSLClient client;
void printWiFiStatus() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());
  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}


void getResponseServer() {
  Serial.println(F("\nUbidots' Server response:\n"));
  while (client.available()) {
    char c = client.read();
   // Serial.print(c); // Uncomment this line to visualize the response on the Serial Monitor
  }
}


void waitServer() {
  int timeout = 0;
  while (!client.available() && timeout < 5000) {
    timeout++;
    delay(1);
    if (timeout >= 5000) {
      Serial.println(F("Error, max timeout reached"));
      break;
    }
  }
}


void sendData(char* payload) {
  int contentLength = strlen(payload);


  /* Connecting the client */
  if (client.connect(SERVER, HTTPPORT)) {
    Serial.println("connected to server");

    client.print(F("POST "));
    client.print(PATH); 
    client.print(DEVICE_LABEL);
    client.print(F("/"));
    client.print(HTTP_VERSION);
    client.print(F("Host: "));
    client.print(SERVER);
    client.print(F("\r\n"));
    client.print(F("User-Agent: "));
    client.print(AGENT);
    client.print(F("\r\n"));
    client.print(F("X-Auth-Token: "));
    client.print(TOKEN);
    client.print(F("\r\n"));
    client.print(F("Connection: close\r\n"));
    client.print(F("Content-Type: application/json\r\n"));
    client.print(F("Content-Length: "));
    client.print(contentLength);
    client.print(F("\r\n\r\n"));
    client.print(payload);
    client.print(F("\r\n"));

    Serial.print(F("POST "));
    Serial.print(PATH); 
    Serial.print(DEVICE_LABEL);
    Serial.print(F("/"));
    Serial.print(HTTP_VERSION);
    Serial.print(F("Host: "));
    Serial.print(SERVER);
    Serial.print(F("\r\n"));
    Serial.print(F("User-Agent: "));
    Serial.print(AGENT);
    Serial.print(F("\r\n"));
    Serial.print(F("X-Auth-Token: "));
    Serial.print(TOKEN);
    Serial.print(F("\r\n"));
    Serial.print(F("Connection: close\r\n"));
    Serial.print(F("Content-Type: application/json\r\n"));
    Serial.print(F("Content-Length: "));
    Serial.print(contentLength);
    Serial.print(F("\r\n\r\n"));
    Serial.print(payload);
    Serial.print(F("\r\n"));

    waitServer();
    getResponseServer();
  }


    /* Disconnecting the client */
  client.stop();
}


//acc & gyro
void AGinit(void)
{


   if (!IMU.begin()) {
    Serial.println("Failed to initialize IMU!");


    while (1);
  }
  Serial.print("Accelerometer sample rate = ");
  Serial.print(IMU.accelerationSampleRate());
  Serial.println(" Hz");
  Serial.println();
  Serial.println("Acceleration in G's");
  Serial.println("X\tY\tZ");


    Serial.print("Gyroscope sample rate = ");
  Serial.print(IMU.gyroscopeSampleRate());
  Serial.println(" Hz");
  Serial.println();
  Serial.println("Gyroscope in degrees/second");
  Serial.println("Gx\tGy\tGz");
  }
void AG_loop(void){

  if (IMU.accelerationAvailable()) {
      IMU.readAcceleration(x, y, z);
  }


  if (IMU.gyroscopeAvailable()) {
    IMU.readGyroscope(gx, gy, gz);
  }
}




void PID_FAN(void)
{
outemp();


  PIDF_error = temp_analog-setF_temperature  ;//error b/w ST n CT


  PIDF_p = Fkp * PIDF_error;// P value


if((PIDF_error <4)&&(PIDF_error >0))//I in a range
{
       PIDF_i = PIDF_i + (Fki * PIDF_error);
     if(!((-20<PIDF_i)&&(PIDF_i<100)))PIDF_i=0;


}


  //derivative-real time: speed change rate
  timePrevF = TimeF;                            // pre time str
  TimeF = millis();                            // actual time read
  elapsedTimeF = (TimeF - timePrevF) / 1000;

  //D Value
  PIDF_d = Fkd*((PIDF_error -  previousF_error)/elapsedTimeF);

  PIDF_value = PIDF_p + PIDF_i + PIDF_d;// P + I + D

  //PWM b/w 0 and 1200
      if(PIDF_value < 900)
      {    PIDF_value =900 ;
  
      }
      if(PIDF_value > 1200)
      { 
        PIDF_value = 1200;
      }


  pwmF.analogWrite(PWMF_pin,PIDF_value);
  previousF_error = PIDF_error;     //Remember to store the previous error for next loop.

}


void PID_TEC(void){
   Innertemp();
  previous_error = PID_error;     //Remember to store the previous error for next loop.


PID_error =tempdigi-set_temperature  ;//error b/w ST n CT


  PID_p = kp * PID_error;// P value


if((PID_error <1.5)&&(PID_error >0))//I in a range
  {
  
    PID_i = PID_i + (ki * PID_error);
   if(!((-10<PID_i)&&(PID_i<10)))PID_i=0;
  }


  //derivative-real time: speed change rate
  timePrev = Time;                            // pre time str
  Time = millis();                            // actual time read
  elapsedTime = (Time - timePrev) / 1000;

  //D Value
  PID_d = kd*((PID_error - previous_error)/elapsedTime);

  PID_value = PID_p + PID_i + PID_d;// P + I + D


  //PWM b/w 0 and 1200
  if(PID_value < 0)
  {    
    PID_value = 0;

  }
if(PID_value > 1200)
  {   PID_value = 1200;


  }

   pwmT.analogWrite(PWM_pin,PID_value);
  previous_error = PID_error;     //Remember to store the previous error for next loop.
// p=255-PID_value;
}


//digital_temp
void Innertemp(void)
{
  //inside temp
  sensors.requestTemperatures();
tempdigi = sensors.getTempCByIndex(0);

}


//analog_temp
void outemp(void)
{

  Vo = analogRead(0);
  R2 = R1 * (1023.0 / (float)Vo - 1.0); //calculate resistance on thermistor
  logR2 = log(R2);
  temp_analog = (1.0 / (c1 + c2*logR2 + c3*logR2*logR2*logR2)); // temperature in Kelvin
  temp_analog = temp_analog - 273.15; //convert Kelvin to Celcius
}
void wifi_init(void)
{
   // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  // attempt to connect to WiFi network:
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(SSID_NAME);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(SSID_NAME, SSID_PASS);
    // wait 10 seconds for connection:
    delay(10000);
  }
  Serial.println("Connected to wifi");
  printWiFiStatus();
  }


void wifi_main(void)
{
  char payload[600];
  //Init_temp
char str_val_1[30];


//set_temperature
//tempdigi
char str_val_2[30];
char str_val_3[30];

/*
PID_error
PID_p
PID_i
PID_d
PID_value
*/
char str_val_4[30];
char str_val_5[30];
char str_val_6[30];
char str_val_7[30];
char str_val_8[30];

/*
setF_temperature
temp_analog
*/
char str_val_9[30];
char str_val_10[30];


/*
PIDF_error
PIDF_p
PIDF_i
PIDF_d
PIDF_value
*/
  char str_val_11[30];
char str_val_12[30];
char str_val_13[30];
char str_val_14[30];
char str_val_15[30];

/*
x
y
z
  */
char str_val_16[30];
char str_val_17[30];
char str_val_18[30];

/*
gx
gy
gz
  */
char str_val_19[30];
char str_val_20[30];
char str_val_21[30];


  /*4 is the total lenght of number,maximun number accepted is 99.99*/
// float value = analogRead(A0);

    dtostrf(set_temperature, 4, 2, str_val_2);
    dtostrf(tempdigi, 4, 2, str_val_3);




    dtostrf(PID_value, 4, 2, str_val_8);

    dtostrf(setF_temperature, 4, 2, str_val_9);
    dtostrf(temp_analog, 4, 2, str_val_10);


    dtostrf(PIDF_value, 4, 2, str_val_15);


   dtostrf(x, 4, 2, str_val_16);
   dtostrf(y, 4, 2, str_val_17);
   dtostrf(z, 4, 2, str_val_18);
  
    dtostrf(gx, 4, 2, str_val_19);
    dtostrf(gy, 4, 2, str_val_20);
    dtostrf(gz, 4, 2, str_val_21);


sprintf(payload, "{\"");
  sprintf(payload, "%s%s\":%s", payload, VARIABLE_LABEL_2, str_val_2);

  sprintf(payload, "%s,\"%s\":%s", payload, VARIABLE_LABEL_3, str_val_3);
   sprintf(payload, "%s,\"%s\":%s", payload, VARIABLE_LABEL_9, str_val_9);
  sprintf(payload, "%s,\"%s\":%s", payload, VARIABLE_LABEL_10, str_val_10);


  sprintf(payload, "%s,\"%s\":%s", payload, VARIABLE_LABEL_16, str_val_16);
  sprintf(payload, "%s,\"%s\":%s", payload, VARIABLE_LABEL_17, str_val_17);
  sprintf(payload, "%s,\"%s\":%s", payload, VARIABLE_LABEL_18, str_val_18);
  sprintf(payload, "%s,\"%s\":%s", payload, VARIABLE_LABEL_19, str_val_19);
  sprintf(payload, "%s,\"%s\":%s", payload, VARIABLE_LABEL_20, str_val_20);
  sprintf(payload, "%s,\"%s\":%s", payload, VARIABLE_LABEL_21, str_val_21);
  sprintf(payload, "%s}", payload);


  //Send the payload to Ubidots
  sendData(payload);
  delay(100);
  }
void setup() {
   Serial.begin(9600);
//  pinMode(PWM_pin,OUTPUT);
   //  pinMode(PWMF_pin,OUTPUT);






////fan pwm
pwmF.setClockDivider(1, false); // Main clock divided by 200 => 240KHz
  pwmF.timer(2, 2, 1200, false);   // Use timer 2 for pin 13, divide clock by 4, resolution 60000, dual-slope PWM
  //pwm.analogWrite(11, 500);        // PWM frequency is now 0.5Hz, dutycycle is 500 / 1000 * 100% = 50%
////////  
///
AGinit();
///
////TEC pwm
pwmT.setClockDivider(1, false); // Main clock divided by 200 => 240KHz
  pwmT.timer(0, 2, 1200, false);   // Use timer 0 for pin 5, divide clock by 4, resolution 60000, dual-slope PWM


   pinMode(in1, OUTPUT);
   pinMode(in2, OUTPUT);
   digitalWrite(in1, HIGH);
   digitalWrite(in2, LOW);

     pinMode(in3, OUTPUT);
   pinMode(in4, OUTPUT);
   digitalWrite(in4, HIGH);
   digitalWrite(in3, LOW);
  // Start up the library
  sensors.begin();
wifi_init();
}

void loop(void)
{
Time = millis(); //Number of milliseconds passed since the program started
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);

digitalWrite(in4, HIGH);
digitalWrite(in3, LOW);

    PID_TEC();
    PID_FAN();
    AG_loop();
    wifi_main();
}

 

Topics

Blogs#

VACBAG   Portable Vaccine Box (Application Of Thermoelectric Cooling) ----Blog#1 "Overview n Progress"Blog#1
VACBAG "Overall Schematic"  Blog#2
VACBAG (IoT Dashboard Live Parameters) Blog#3
VACBAG-- SYSTEM CONTROL Blog#4
VACBAG 'CODE' Blog#5
VACBAG "Performance curves"Blog#6
VACBAG Machine Learning Model-Door_check || System ON || System OFF || System Anomaly Blog#7
VACBAG---"PRODUCT"Blog#8