0% found this document useful (0 votes)
120 views37 pages

Janhavi IoT

The document is a certificate certifying that Janhavi Ghogle has successfully completed CSC420 - Introduction to IoT practice sessions as part of her 4th year B.Tech in Computer Engineering at Ajeenkya D Y Patil University, Pune for the academic year 2022-23. It contains the signatures of the faculty in-charge and head of the school of engineering. The rest of the document contains program code snippets and outputs for interfacing Arduino with various sensors, displays, motors and other IoT devices as part of the course assignments.

Uploaded by

Janhavi Ghogle
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
120 views37 pages

Janhavi IoT

The document is a certificate certifying that Janhavi Ghogle has successfully completed CSC420 - Introduction to IoT practice sessions as part of her 4th year B.Tech in Computer Engineering at Ajeenkya D Y Patil University, Pune for the academic year 2022-23. It contains the signatures of the faculty in-charge and head of the school of engineering. The rest of the document contains program code snippets and outputs for interfacing Arduino with various sensors, displays, motors and other IoT devices as part of the course assignments.

Uploaded by

Janhavi Ghogle
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

CSC420 – Introduction to IoT

Bachelor of Technology

SEMESTER – VII
YEAR 2022

Name: Janhavi Ghogle

URN: 2019-B-28092001

School of Engineering
Ajeenkya D Y Patil University, Pune

DY Patil Knowledge City Road Via Lohegaon,


Airport Rd, Charholi Budruk, Pune, Maharashtra 412105
1
DATE: 20th November 2022

CERTIFICATE

This is to certify that Miss Janhavi Ghogle bearing URN number 2019-B-

28092001 of B. Tech 4th year Computer Engineering has successfully completed

CSC420 – Introduction to IoT practice session as per the university requirements

during the academic year 2022-23.

Dr. Raj Gaurav Mishra Dr. Biswajeet Champaty


Faculty In-charge Head-School of Engineering

2
INDEX
Sr. No. Problem Statements / Exercise Page NO. C-D-I-O
(Model)
1 Write a program using Arduino IDE for blinking 1 I
LED.
2 Write a program for RGB LED using Arduino. 2 I
3 Write a program to Interface five different 4 I
sensors with Arduino Uno.
4 Write a program to Interface Arduino Uno with 7 I
motors (stepper and servo).
5 Write a program to Interface Arduino Uno with 9 I
relays and buzzer.
6 Write a program to Interface Arduino Uno with 10 I
LCD display.
7 Write a program to Interface Arduino Uno with 12 I
ESP8266WiFi module.
8 Write a program to Interface Arduino Uno with 14 I
HC05/06 Bluetooth module.
9 Study and implement MQTT protocol using 16 I
Arduino Uno.
10 Write a program to build your custom app to 22 I
control Arduino Uno.
11 IoT based mini project 24 I

3
Sl No.1:
Write a program using Arduino IDE for blinking LED.

Code:
void setup() {  // initialize digital pin 13 as an output.
   pinMode(2, OUTPUT);
}

loop() {
   digitalWrite(2, HIGH); // turn the LED on (HIGH is the voltage level)
   delay(1000); // wait for a second
   digitalWrite(2, LOW); // turn the LED off by making the voltage LOW
   delay(1000); // wait for a second
}

Output:

1
Sl No.2:
Write a program for RGB LED using Arduino.

Code:
int red_light_pin= 11;
int green_light_pin = 5;
int blue_light_pin = 2;

void setup() {
  pinMode(red_light_pin, OUTPUT);
  pinMode(green_light_pin, OUTPUT);
  pinMode(blue_light_pin, OUTPUT);
}
void loop() {
  RGB_color(255, 0, 0); // Red
  delay(1000);
  RGB_color(0, 255, 0); // Green
  delay(1000);
  RGB_color(0, 0, 255); // Blue
  delay(1000);
  RGB_color(255, 255, 125); // Raspberry
  delay(1000);
  RGB_color(0, 255, 255); // Cyan

  delay(1000);
  RGB_color(255, 0, 255); // Magenta
  delay(1000);
  RGB_color(255, 255, 0); // Yellow
  delay(1000);
  RGB_color(255, 255, 255); // White
  delay(1000);
}
void RGB_color(int red_light_value, int green_light_value, int blue_light_value)
 {
  analogWrite(red_light_pin, red_light_value);
  analogWrite(green_light_pin, green_light_value);
  analogWrite(blue_light_pin, blue_light_value);
}

2
Output:

3
Sl No.3:
Write a program to Interface five different sensors with Arduino Uno.

Code:
#include "DHT.h"
#include <LiquidCrystal_I2C.h>

const float GAMMA = 0.7;


const float RL10 = 50;

#define DHTPIN 2    
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
#define LDR_PIN 2
#define trigPin 10
#define echoPin 9

long duration; // variable for the duration of sound wave travel


int distance; // variable for the distance measurement
int sensor = A1.
int state = LOW;           // by default, no motion detected
int val = 0;

DHT dht(DHTPIN, DHTTYPE);


int ctr = 0;
void setup() {
  Serial.begin(115200);
  Serial.println(F("DHT22 example!"));
  pinMode(A0, INPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
  pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
  pinMode(sensor, INPUT);
  dht.begin();
}

void loop() {
  float temperature = dht.readTemperature();
4
  float humidity = dht.readHumidity();

  // Check if any reads failed and exit early (to try again).
  if (isnan(temperature) || isnan(humidity)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }

int analogValue = analogRead(A0); // Convert the analog value into lux value:
float voltage = analogValue / 1024. * 5;
float resistance = 2000 * voltage / (1 - voltage / 5);
float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));

  Serial.print(F("Humidity: "));
  Serial.print(humidity);
  Serial.println(F("% "));
 
  Serial.print(F("Temperature: "));
  Serial.print(temperature);
  Serial.println(F("°C "));

  Serial.print("Lux: ");
  Serial.println(lux);

  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin HIGH (ACTIVE) for 10 microseconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance = duration * 0.034 / 2; // Speed of sound wave divided by 2
  // Displays the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

   val = digitalRead(sensor); // read sensor value


  if (val == HIGH) {           // check if the sensor is HIGH

5
   
    if (state == LOW) {
      Serial.println("Motion detected!");
      state = HIGH;       // update variable state to HIGH
    }
  }
  else {
      if (state == HIGH){
        Serial.println("Motion stopped!");
        state = LOW;       // update variable state to LOW
    }
  }
   delay(2000); // Wait a few seconds between measurements
}

Output:

6
Sl No.4:
Write a program to Interface Arduino Uno with motors (stepper and servo).

Code:
/*

  Stepper Motor A4988 Driver Example

  No code here - use the pushbutton to rotate a single step, and the switch to
control the direction

*/
#include <Servo.h>

Servo myservo;  // create servo object to control a servo


// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(5);  // attaches the servo on pin 5 to the servo object
}

void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable
'pos'
    delay(15);                       // waits 15ms for the servo to reach the
position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable
'pos'
    delay(15);                       // waits 15ms for the servo to reach the
position
  }
}
7
Output:

8
Sl No.5:
Write a program to Interface Arduino Uno with relays and buzzer.

Code:
const int relayPin = 13;

void setup()
{
  pinMode( relayPin, OUTPUT);
  }

void loop()
{
  digitalWrite( relayPin, HIGH);
  delay( 600);
  digitalWrite( relayPin, LOW);
  delay( 600);
}

Output:

9
Sl No.6:
Write a program to Interface Arduino Uno with LCD display.

Code:
// include the library code:
#include <LiquidCrystal.h>

// initialize the library by associating any needed LCD interface pin


// with the arduino pin number it is connected to
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("    Janhavi");

void loop() {
  // Turn off the display:
  lcd.noDisplay();
  delay(500);
  // Turn on the display:
  lcd.display();
  delay(500);
}

10
Output:

11
Sl No.7:
Write a program to Interface Arduino Uno with ESP8266WiFi module.

Code:
#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

char auth[ ] = "yeR2X7rBxSnBeJXc0SzAEUVe3fv0km_t";


char ssid[ ] = "GHOGLE";
char pass[ ] = "98330129";

WidgetLED led1(V1);
BlynkTimer timer;

// V1 LED Widget is blinking


void blinkLedWidget()  // function for switching off and on LED
{
  if (led1.getValue()) {
    led1.off();
    Serial.println("LED on V1: off");
  } else {
    led1.on();
    Serial.println("LED on V1: on");
  }
}

void setup()
{
  Serial.begin(9600);
  Blynk.begin(auth, ssid, pass);
  timer.setInterval(1000L, blinkLedWidget);
}

void loop()
{
  Blynk.run();
  timer.run();
}

12
Output:

13
Sl No.8:
Write a program to Interface Arduino Uno with HC05/06 Bluetooth module.

Code:
char Incoming_value = 0; //Variable for storing
Incoming_value
void setup()
{
Serial.begin(9600); //Sets the data rate in bits per second
(baud) for serial data transmission
pinMode(13, OUTPUT); //Sets digital pin 13 as output pin
}
void loop()
{
if(Serial.available() > 0)
{
Incoming_value = Serial.read(); //Read the incoming data and
store it into variable Incoming_value
Serial.print(Incoming_value); //Print Value of
Incoming_value in Serial monitor
Serial.print("\n"); //New line
if(Incoming_value == '1') //Checks whether value of
Incoming_value is equal to 1
digitalWrite(13, HIGH); //If value is 1 then LED turns ON
else if(Incoming_value == '0') //Checks whether value of
Incoming_value is equal to 0
digitalWrite(13, LOW); //If value is 0 then LED turns OFF
}

14
Output:

15
Sl No.9:
Study and implement MQTT protocol using Arduino Uno.

Code:
SUBSCRIBER:
#include <ArduinoMqttClient.h>
#include <WiFiNINA.h>
#include "arduino_secrets.h"

///////please enter your sensitive data in the Secret tab/arduino_secrets.h


char ssid[] = "GHOGLE";        // your network SSID (name)
char pass[] = "98330129";    // your network password (use for WPA, or use as key
for WEP)

WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);

const char broker[] = "test.mosquitto.org";


int        port     = 1883;
const char topic[]  = "real_unique_topic";
const char topic2[]  = "real_unique_topic_2";
const char topic3[]  = "real_unique_topic_3";

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  // attempt to connect to Wifi network:
  Serial.print("Attempting to connect to SSID: ");
  Serial.println(ssid);
  while (WiFi.begin(ssid, pass)! = WL_CONNECTED) {
    // failed, retry
    Serial.print(".");
    delay(5000);
  }

  Serial.println("You're connected to the network");


16
  Serial.println();

  Serial.print("Attempting to connect to the MQTT broker: ");


  Serial.println(broker);

  if (!mqttClient.connect(broker, port)) {
    Serial.print("MQTT connection failed! Error code = ");
    Serial.println(mqttClient.connectError());

    while (1);
  }

  Serial.println("You're connected to the MQTT broker!");


  Serial.println();

  // set the message receive callback


  mqttClient.onMessage(onMqttMessage);

  Serial.print("Subscribing to topic: ");


  Serial.println(topic);
  Serial.println();

  // subscribe to a topic
  mqttClient.subscribe(topic);
  mqttClient.subscribe(topic2);
  mqttClient.subscribe(topic3);

  // topics can be unsubscribed using:


  // mqttClient.unsubscribe(topic);

  Serial.print("Topic: ");
  Serial.println(topic);
  Serial.print("Topic: ");
  Serial.println(topic2);
  Serial.print("Topic: ");
  Serial.println(topic3);

  Serial.println();
}

void loop() {

17
  // call poll() regularly to allow the library to receive MQTT messages and
  // send MQTT keep alive which avoids being disconnected by the broker
  mqttClient.poll();
}

void onMqttMessage(int messageSize) {


  // we received a message, print out the topic and contents
  Serial.println("Received a message with topic '");
  Serial.print(mqttClient.messageTopic());
  Serial.print("', length ");
  Serial.print(messageSize);
  Serial.println(" bytes:");

  // use the Stream interface to print the contents


  while (mqttClient.available()) {
    Serial.print((char)mqttClient.read());
  }
  Serial.println();
  Serial.println();
}

PUBLISHER:
#include <ArduinoMqttClient.h>
#include <WiFiNINA.h>
#include "arduino_secrets.h"

///////please enter your sensitive data in the Secret tab/arduino_secrets.h


char ssid[] = "GHOGLE";       // your network SSID (name)
char pass[] = "98330129";    // your network password (use for WPA, or use as key
for WEP)

WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);

const char broker[] = "test.mosquitto.org";


int        port     = 1883;
const char topic[]  = "real_unique_topic";
const char topic2[]  = "real_unique_topic_2";
const char topic3[]  = "real_unique_topic_3";

18
//set interval for sending messages (milliseconds)
const long interval = 8000;
unsigned long previousMillis = 0;

int count = 0;

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // attempt to connect to Wifi network:


  Serial.print("Attempting to connect to WPA SSID: ");
  Serial.println(ssid);
  while (WiFi.begin(ssid, pass) != WL_CONNECTED) {
    // failed, retry
    Serial.print(".");
    delay(5000);
  }

  Serial.println("You're connected to the network");


  Serial.println();

  Serial.print("Attempting to connect to the MQTT broker: ");


  Serial.println(broker);

  if (!mqttClient.connect(broker, port)) {
    Serial.print("MQTT connection failed! Error code = ");
    Serial.println(mqttClient.connectError());

    while (1);
  }

  Serial.println("You're connected to the MQTT broker!");


  Serial.println();
}

void loop() {
  // call poll() regularly to allow the library to send MQTT keep alive which

19
  // avoids being disconnected by the broker
  mqttClient.poll();

  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {


    // save the last time a message was sent
    previousMillis = currentMillis;

    //record random value from A0, A1 and A2


    int Rvalue = analogRead(A0);
    int Rvalue2 = analogRead(A1);
    int Rvalue3 = analogRead(A2);

    Serial.print("Sending message to topic: ");


    Serial.println(topic);
    Serial.println(Rvalue);

    Serial.print("Sending message to topic: ");


    Serial.println(topic2);
    Serial.println(Rvalue2);

    Serial.print("Sending message to topic: ");


    Serial.println(topic3);
    Serial.println(Rvalue3);

    // send message, the Print interface can be used to set the message contents
    mqttClient.beginMessage(topic);
    mqttClient.print(Rvalue);
    mqttClient.endMessage();

    mqttClient.beginMessage(topic2);
    mqttClient.print(Rvalue2);
    mqttClient.endMessage();

    mqttClient.beginMessage(topic3);
    mqttClient.print(Rvalue3);
    mqttClient.endMessage();

    Serial.println();
  }

20
}

Output:

21
Sl No.10:
Write a program to build your custom app to control Arduino Uno.
Code:
#define BLYNK_PRINT Serial
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

char auth[ ] = "yeR2X7rBxSnBeJXc0SzAEUVe3fv0km_t";


char ssid[ ] = "GHOGLE";
char pass[ ] = "98330129";

WidgetLED led1(V1);
BlynkTimer timer;

// V1 LED Widget is blinking


void blinkLedWidget()  // function for switching off and on LED
{
  if (led1.getValue()) {
    led1.off();
    Serial.println("LED on V1: off");
  } else {
    led1.on();
    Serial.println("LED on V1: on");
  }
}

void setup()
{
  Serial.begin(9600);
  Blynk.begin(auth, ssid, pass);
  timer.setInterval(1000L, blinkLedWidget);
}

void loop()
{
  Blynk.run();
  timer.run();
}

22
Output:

23
Sl No.11:
IoT based mini project

Introduction:
Using basic electronics and sensor array, we produce affordable and reliable
reading of biological data.

Hardware:
1. TP4056 Controller
2. AD8232 ECG Monitor Sensor
3. Arduino Pro Mini
4. Node MCU 1.0
5. TM4506 Power Supply Module

CODE:
/*
Optical SP02 Detection (SPK Algorithm) using the MAX30105 Breakout
By: Nathan Seidle @ SparkFun Electronics
Date: October 19th, 2016
https://github.com/sparkfun/MAX30105_Breakout

This demo shows heart rate and SPO2 levels.

It is best to attach the sensor to your finger using a rubber band or other tightening device.
Humans are bad at applying constant pressure to a thing. When you press your finger against
the sensor it varies enough to cause the blood in your finger to flow differegenerallyntly which
causes the sensor readings to go wonky.

This example is based on MAXREFDES117 and RD117_LILYPAD.ino from Maxim. Their


example was modified to work with the SparkFun MAX30105 library and to compile under
Arduino 1.6.11
Please see license file for more info.

Hardware Connections (Breakoutboard to Arduino):


-5V = 5V (3.3V is allowed)
-GND = GND

24
-SDA = A4 (or SDA)
-SCL = A5 (or SCL)
-INT = Not connected

The MAX30105 Breakout can handle 5V or 3.3V I2C logic. We recommend powering the board
with 5V but it will also run at 3.3V.
*/

#include <SoftwareSerial.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <Arduino_JSON.h>
#include <Wire.h>
#include "MAX30105.h"
#include "spo2_algorithm.h"
#define String httpGETRequest(const char* serverName)
//MAX30105 particleSensor;

const char* ssid = "GHOGLE";


const char* password = "98330129";

const char* serverName = "http://192.168.220.1:1880/#flow/4d413697c097176e"; //Your


Domain name with URL path or IP address with path

unsigned long lastTime = 0;


unsigned long timerDelay = 5000; // Set timer to 5 seconds (5000)

#define MAX_BRIGHTNESS 255

#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)


//Arduino Uno doesn't have enough SRAM to store 100 samples of IR led data and red led data
in 32-bit format
//To solve this problem, 16-bit MSB of the sampled data will be truncated. Samples become 16-
bit data.
uint16_t irBuffer[100]; //infrared LED sensor data
uint16_t redBuffer[100]; //red LED sensor data

#else
uint32_t irBuffer[100]; //infrared LED sensor data

25
uint32_t redBuffer[100]; //red LED sensor data

#endif
int32_t bufferLength; //data length
int32_t spo2; //SPO2 value
int8_t validSPO2; //indicator to show if the SPO2 calculation is valid
int32_t heartRate; //heart rate value
int8_t validHeartRate; //indicator to show if the heart rate calculation is valid

byte pulseLED = 11; //Must be on PWM pin


byte readLED = 13; //Blinks with each data read

SoftwareSerial nodemcuu(,); // Establishing connection between Arduino and NodeMCU


void setup()
{
Serial.begin(115200); // initialize serial communication at 115200 bits per second:
nodemcu.begin(115200);

pinMode(pulseLED, OUTPUT);
pinMode(readLED, OUTPUT);

pinMode(A0, INPUT);
pinMode(10, INPUT);
pinMode(11, INPUT);
pinMode(5, INPUT);

// Initialize sensor
if (!particleSensor.begin(Wire, I2C_SPEED_FAST)) //Use default I2C port, 400kHz speed
{
Serial.println(F("MAX30105 was not found. Please check wiring/power."));
while (1);
}
/*
Serial.println(F("Attach sensor to finger with rubber band. Press any key to start conversion"));
while (Serial.available() == 0) ; //wait until user presses a key
Serial.read();
*/

byte ledBrightness = 60; //Options: 0=Off to 255=50mA

26
byte sampleAverage = 4; //Options: 1, 2, 4, 8, 16, 32
byte ledMode = 2; //Options: 1 = Red only, 2 = Red + IR, 3 = Red + IR + Green
byte sampleRate = 100; //Options: 50, 100, 200, 400, 800, 1000, 1600, 3200
int pulseWidth = 411; //Options: 69, 118, 215, 411
int adcRange = 4096; //Options: 2048, 4096, 8192, 16384

particleSensor.setup(ledBrightness, sampleAverage, ledMode, sampleRate, pulseWidth,


adcRange); //Configure sensor with these settings

Serial.println("RedValue, IR Value, Raw Heart Value, HearRate, SpO2, ecg");

Serial.begin(115200);

WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());

Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before


publishing the first reading.");

void loop()
{

//Send an HTTP POST request every 10 minutes


if ((millis() - lastTime) > timerDelay)
{
//Check WiFi connection status
if(WiFi.status()== WL_CONNECTED)
{
WiFiClient client;

27
HTTPClient http;
sensorReadings = httpGETRequest(serverName);
Serial.println(sensorReadings);
JSONVar myObject = JSON.parse(sensorReadings);

// JSON.typeof(jsonVar) can be used to get the type of the var


if (JSON.typeof(myObject) == "undefined")
{
Serial.println("Parsing input failed!");
return;
}

StaticJsonDocument<1000> doc; //Json declaration


Processing(); // obtain data from sensors

doc["red"] = values[0];
doc["IR"] = values[1];
doc["Spo2"] = values[2];
doc["ECG"] = values[3];

serialization(doc, nodemcu); // Send data to ModeMCU


}
else
{
Serial.println("WiFi Disconnected");
}
lastTime = millis();

delay(1000);
}
}

int Processing()
{
bufferLength = 100; //buffer length of 100 stores 4 seconds of samples running at 25sps

//read the first 100 samples, and determine the signal range
for (byte i = 0 ; i < bufferLength ; i++)
{

28
while (particleSensor.available() == false) //do we have new data?
particleSensor.check(); //Check the sensor for new data

redBuffer[i] = particleSensor.getRed();
irBuffer[i] = particleSensor.getIR();
particleSensor.nextSample(); //We're finished with this sample so move to next sample
/*
Serial.print(F("red="));
Serial.print(redBuffer[i], DEC);
Serial.print(F(", ir="));
Serial.println(irBuffer[i], DEC);
*/
}

//calculate heart rate and SpO2 after first 100 samples (first 4 seconds of samples)
maxim_heart_rate_and_oxygen_saturation(irBuffer, bufferLength, redBuffer, &spo2,
&validSPO2, &heartRate, &validHeartRate);

//Continuously taking samples from MAX30102. Heart rate and SpO2 are calculated every 1
second
while (1)
{
if(digitalRead(5)==1)
{
for(int x=0; x<10; x++)
{
//dumping the first 25 sets of samples in the memory and shift the last 75 sets of samples to
the top
for (byte i = 25; i < 100; i++)
{
redBuffer[i - 25] = redBuffer[i];
irBuffer[i - 25] = irBuffer[i];
}

//take 25 sets of samples before calculating the heart rate.


for (byte i = 75; i < 100; i++)
{
while (particleSensor.available() == false) //do we have new data?
particleSensor.check(); //Check the sensor for new data

29
digitalWrite(readLED, !digitalRead(readLED)); //Blink onboard LED with every data read

redBuffer[i] = particleSensor.getRed();
irBuffer[i] = particleSensor.getIR();
particleSensor.nextSample(); //We're finished with this sample so move to next sample

//send samples and calculation result to terminal program through UART

//Serial.print(x);
//Serial.print(',');

//Serial.print(F("red="));
Serial.print(redBuffer[i], DEC);
Serial.print(',');

//Serial.print(F(", ir="));
Serial.print(irBuffer[i], DEC);
Serial.print(',');

//Serial.print(F(", HR="));
Serial.print(heartRate, DEC);
Serial.print(',');

//Serial.print(F(", HRvalid="));
//Serial.print(validHeartRate, DEC);

//Serial.print(F(", SPO2="));
Serial.print(spo2, DEC);
//Serial.print(',');

//ecg
Serial.println(analogRead(A0));

//Serial.print(F(", SPO2Valid="));
//Serial.println(validSPO2, DEC);
}

//After gathering 25 new samples recalculate HR and SP02


maxim_heart_rate_and_oxygen_saturation(irBuffer, bufferLength, redBuffer, &spo2,
&validSPO2, &heartRate, &validHeartRate);
30
uint8_t values[4];

values[0] = redBuffer;
values[1] = irBuffer;
values[2] = spo2;
values[3] = analogRead(A0);

return values;

}
}
}
}

String httpGETRequest(const char* serverName);


{
WiFiClient client;
HTTPClient http;

// Your IP address with path or Domain name with URL path


http.begin(client, serverName);

// Send HTTP POST request


int httpResponseCode = http.GET();

String payload = "{}";

if (httpResponseCode>0)
{
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
payload = http.getString();
}
else
{
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}

31
// Free resources
http.end();

return payload;
}

Node Red Flow:

32
Circuit:

33
34

You might also like