Program to display heart rate and heart beat waveform based on photoplethysmography (PPG). It reads values from a sensor made of photodiode and LED and displays the corresponding heart rate and waveform on an LCD screen
The document discusses several greedy algorithm problems:
1. The knapsack problem which involves filling a knapsack with objects to maximize total value while not exceeding weight capacity. Objects are sorted by value/weight ratio.
2. The chemistry reagents problem which involves storing reagents in refrigerators where each refrigerator has a set temperature. The minimum number of refrigerators is determined.
3. The overlapping circles problem which counts the maximum number of exterior circles on an x-axis where each circle is defined by its center and radius. Intervals are sorted and a maximum number of disjoint intervals is found.
How to add an optimization for C# to RyuJITEgor Bogatov
This document discusses various ways to optimize C# code by adding custom optimizations to the JIT compiler. It begins by explaining how to morph the intermediate representation (IR) tree during JIT compilation to optimize expressions like dividing by a constant. It then covers implementing range check elimination, loop optimizations like invariant code hoisting, and ideas for optimizations not yet implemented like loop unrolling and deletion. The goal is to explore how to most easily add optimizations by modifying phases in the JIT compiler.
This document discusses connecting an Arduino Micro to an XBee module for wireless serial communication. It describes sending accelerometer data from the Arduino over serial using a comma separated value format of "id,x,y,z". It also discusses receiving this data in openFrameworks by reading from the serial port byte by byte and parsing the values. The values are then rescaled and drawn to the screen based on their range of 0-1023 mapping to the window width.
The document describes using an Arduino Micro to read acceleration and gyroscope values from an MPU-6050 sensor module over I2C. It connects the sensor to the Arduino, initializes the sensor library, sets the sensor ranges, and reads the signed 16-bit acceleration and rotation values. It transmits the sensor ID and acceleration/gyroscope values over serial to an openFrameworks application, which splits the received string into numbers and draws a rectangle representing the acceleration value.
The document discusses microbenchmarking and factors that can affect benchmark results such as hardware, software environments, optimizations, caching, and isolation of tests. It provides examples of benchmarks that examine effects like branch prediction, interface dispatch, inlining, and SIMD vectorization. Benchmarks that calculate square roots demonstrate how a JIT compiler may optimize repetitive calculations. The document emphasizes the importance of controlling variables, using statistical analysis of multiple runs, isolating tests, and understanding how systems like caches and branch predictors can skew results.
The document discusses different types of linked lists including singly linked lists, doubly linked lists, and circular linked lists. It provides examples of how to implement these linked lists in C by defining node structures containing data fields and pointer fields. The document also demonstrates how to perform operations on linked lists such as inserting nodes, deleting nodes, and finding the middle node.
A Speculative Technique for Auto-Memoization Processor with MultithreadingMatsuo and Tsumura lab.
Yushi KAMIYA, Tomoaki TSUMURA, Hiroshi MATSUO, Yasuhiko NAKASHIMA:
"A Speculative Technique for Auto-Memoization Processor with Multithreading"(発表資料)
Proc. 10th Intl. Conf. on Parallel and Distributed Computing, Applications and Technologies (PDCAT'09), Higashi-Hiroshima, Japan, pp.160-166 (Dec. 2009)
The document discusses several greedy algorithm problems:
1. The knapsack problem which involves filling a knapsack with objects to maximize total value while not exceeding weight capacity. Objects are sorted by value/weight ratio.
2. The chemistry reagents problem which involves storing reagents in refrigerators where each refrigerator has a set temperature. The minimum number of refrigerators is determined.
3. The overlapping circles problem which counts the maximum number of exterior circles on an x-axis where each circle is defined by its center and radius. Intervals are sorted and a maximum number of disjoint intervals is found.
How to add an optimization for C# to RyuJITEgor Bogatov
This document discusses various ways to optimize C# code by adding custom optimizations to the JIT compiler. It begins by explaining how to morph the intermediate representation (IR) tree during JIT compilation to optimize expressions like dividing by a constant. It then covers implementing range check elimination, loop optimizations like invariant code hoisting, and ideas for optimizations not yet implemented like loop unrolling and deletion. The goal is to explore how to most easily add optimizations by modifying phases in the JIT compiler.
This document discusses connecting an Arduino Micro to an XBee module for wireless serial communication. It describes sending accelerometer data from the Arduino over serial using a comma separated value format of "id,x,y,z". It also discusses receiving this data in openFrameworks by reading from the serial port byte by byte and parsing the values. The values are then rescaled and drawn to the screen based on their range of 0-1023 mapping to the window width.
The document describes using an Arduino Micro to read acceleration and gyroscope values from an MPU-6050 sensor module over I2C. It connects the sensor to the Arduino, initializes the sensor library, sets the sensor ranges, and reads the signed 16-bit acceleration and rotation values. It transmits the sensor ID and acceleration/gyroscope values over serial to an openFrameworks application, which splits the received string into numbers and draws a rectangle representing the acceleration value.
The document discusses microbenchmarking and factors that can affect benchmark results such as hardware, software environments, optimizations, caching, and isolation of tests. It provides examples of benchmarks that examine effects like branch prediction, interface dispatch, inlining, and SIMD vectorization. Benchmarks that calculate square roots demonstrate how a JIT compiler may optimize repetitive calculations. The document emphasizes the importance of controlling variables, using statistical analysis of multiple runs, isolating tests, and understanding how systems like caches and branch predictors can skew results.
The document discusses different types of linked lists including singly linked lists, doubly linked lists, and circular linked lists. It provides examples of how to implement these linked lists in C by defining node structures containing data fields and pointer fields. The document also demonstrates how to perform operations on linked lists such as inserting nodes, deleting nodes, and finding the middle node.
A Speculative Technique for Auto-Memoization Processor with MultithreadingMatsuo and Tsumura lab.
Yushi KAMIYA, Tomoaki TSUMURA, Hiroshi MATSUO, Yasuhiko NAKASHIMA:
"A Speculative Technique for Auto-Memoization Processor with Multithreading"(発表資料)
Proc. 10th Intl. Conf. on Parallel and Distributed Computing, Applications and Technologies (PDCAT'09), Higashi-Hiroshima, Japan, pp.160-166 (Dec. 2009)
This document includes header files and code for interfacing with GPS, compass, and SD card components. It initializes these devices and logs GPS data including latitude, longitude, and fix age to an SD card file. It also calculates distance between the current GPS position and predefined waypoints. The main loop acquires new GPS data every 250ms and prints it to the serial monitor if available.
1. Use nonatomic properties for primitive types like floats to avoid locking.
2. Use CCArray instead of NSMutableArray for better performance in cocos2d. Iterate arrays using CC_ARRAY_FOREACH.
3. Use index access instead of indexOfObject to improve performance of lookups in for loops.
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014PyData
Pythran is a an ahead of time compiler that turns modules written in a large subset of Python into C++ meta-programs that can be compiled into efficient native modules. It targets mainly compute intensive part of the code, hence it comes as no surprise that it focuses on scientific applications that makes extensive use of Numpy. Under the hood, Pythran inter-procedurally analyses the program and performs high level optimizations and parallel code generation. Parallelism can be found implicitly in Python intrinsics or Numpy operations, or explicitly specified by the programmer using OpenMP directives directly in the Python source code. Either way, the input code remains fully compatible with the Python interpreter. While the idea is similar to Parakeet or Numba, the approach differs significantly: the code generation is not performed at runtime but offline. Pythran generates C++11 heavily templated code that makes use of the NT2 meta-programming library and relies on any standard-compliant compiler to generate the binary code. We propose to walk through some examples and benchmarks, exposing the current state of what Pythran provides as well as the limit of the approach.
Bartosz Milewski, “Re-discovering Monads in C++”Platonov Sergey
Once you know what a monad is, you start seeing them everywhere. The std::future library of C++11 was an example of an incomplete design, which stopped short of recognizing the monadic nature of futures. This is now being remedied in C++17, and there are new library additions, like std::expected and the range library, that are much more monad-conscious. I’ll explain what a monad is using copious C++ examples.
The document discusses various techniques for improving OpenGL application performance, including using vertex buffer objects (VBOs) and vertex array objects (VAOs) to store vertex data in graphics memory. It provides an example of creating a cube using VBOs and VAOs to initialize vertex position and color data and load it into a VBO. Display lists are described as allowing geometry to be defined once and executed multiple times to improve performance for redrawing the same geometry. Frustum culling and scissoring are introduced as clipping techniques. General memory management techniques like avoiding frequent memory allocations in loops are also covered.
The document provides source code for generating and manipulating computer graphics using various algorithms. It includes algorithms for drawing lines, circles and curves, as well as algorithms for translating, rotating, and scaling two-dimensional and three-dimensional objects. The source code is written in C/C++ and uses graphics libraries to output the results. Various input parameters are taken from the user and output is displayed to demonstrate the algorithms.
Exploring Color Spaces with Gesture Tracking and Smart Bulbs (Distill 2014)Daniel Luxemburg
The document discusses exploring different color spaces like RGB, HSL, and HSV by tracking hand gestures with a Leap Motion controller and controlling LIFX smart bulbs. Code examples are provided in Ruby and JavaScript to discover LIFX bulbs, map hand position data to color values, and set the bulb colors. The goal is to enable new ways of interacting with technology through gesture control and different representations of color.
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"OdessaJS Conf
Node.js uses the V8 JavaScript engine and the libuv library. V8 compiles JavaScript to machine code for high performance, while libuv provides asynchronous I/O capabilities. Node.js initializes V8, wraps libuv, and provides a module system to load code, with modules defined as functions that export values. Native modules can extend Node.js using NAN or the newer N-API for direct access to V8 from C/C++ code.
This document provides an overview of basic data structures concepts. It discusses bits and data types, different numeric representations like binary and decimal. It introduces common data types used in programming like integers and floats. It also covers abstract data types and provides examples like stacks, queues and lists. The document describes iterative and recursive algorithms for problems like factorial calculation, binary search and the Towers of Hanoi. It analyzes the time complexity of algorithms like selection sort.
The document discusses the implementation of a binary search tree (BST) using both recursive and non-recursive traversal methods. It defines a BST node structure with left and right child pointers. Functions are included to insert nodes, perform inorder, preorder and postorder traversals recursively and non-recursively using stacks. Main inserts sample nodes into the tree and calls the various traversal functions to output the node values in the specified orders.
The document summarizes AA-sort, a sorting algorithm optimized for SIMD and multicore processors. AA-sort works by first sorting blocks of data in parallel using vectorized combsort. It then merges the sorted blocks together. Key steps include sorting 4 elements within each SIMD register, transposing the registers, and performing a vectorized version of combsort without conditional branches. The document provides pseudocode for these steps.
Translating Classic Arcade Games to JavaScriptnorbert_kehrer
This document discusses translating classic arcade games like Asteroids from the 6502 processor to JavaScript. It begins by explaining emulation versus recompilation approaches. It then describes translating the 6502 assembly code to JavaScript by representing registers as variables and memory as arrays. Challenges like conditional branches are addressed. Optimization techniques like redundant flag calculation elimination are discussed, linking the translation to compiler theory topics like liveness analysis. The goal is a browser-playable version of Asteroids that demonstrates translating a real-world 6502 application to JavaScript.
This document provides C code solutions to interface four 7-segment displays on an ARM7 microcontroller and display counts from 0000 to 9999. The code defines arrays to store the digit values for the displays and uses conditions to extract the digits from the count value to display on the individual segments. Delay functions are used to control the timing of digit updates on the displays.
This document discusses using multithreading in Java with LEJOS to control a line following robot. It presents the original single-threaded code and then improves it using two threads - one for line following and one for obstacle detection. The main program starts each thread and uses a DataExchange class to allow the threads to communicate and coordinate the robot's behavior. When no obstacles are detected, the line following thread controls the motors to follow a black line. When an obstacle is detected within 25cm, the obstacle detection thread stops the line following behavior.
The document discusses different approaches to implementing GPU-like programming on CPUs using C++AMP. It covers using setjmp/longjmp to implement coroutines for "fake threading", using ucontext for coroutine context switching, and how to pass lambda functions and non-integer arguments to makecontext. Implementing barriers on CPUs requires synchronizing threads with an atomic counter instead of GPU shared memory. Overall, the document shows it is possible to run GPU-like programming models on CPUs by simulating the GPU programming model using language features for coroutines and threading.
This document contains C++ code to find roots of equations using the bisection method. It includes 4 questions:
1) Finds the root of x3 – 4x – 8.95 = 0 between 2 and 3 to 3 decimal places.
2) Finds the root of ex – 3x = 0 using bisection up to a specified number of iterations.
3) Defines a bisection function to find the root of f(x) = x6 – x – 1 = 0 within 0.001 accuracy.
4) Defines a bisection function to find the smallest positive root of a cubic equation ax3+bx2+cx+d=0 within an error tolerance of 10-6.
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"OdessaJS Conf
This document introduces MetaSync, a library for asynchronous programming in JavaScript. It discusses current asynchronous patterns like callbacks, promises, and async/await and their limitations. MetaSync aims to address these issues through function composition for asynchronous I/O, specific asynchronous abstractions, and a short, expressive syntax. It allows composing asynchronous functions sequentially or in parallel and includes tools like collectors, throttling, and queues to manage asynchronous data and operations.
On using Haskell DSL - CLaSH, to implement a simple digital stopwatch on FPGAmjgajda
This document summarizes a Haskell.SG MeetUp presentation about using the ClaSH compiler plugin to compile Haskell code describing digital logic circuits into VHDL for implementation on FPGAs. The presentation introduced basic digital logic concepts like gates, clocks, registers and three-state logic. It described how ClaSH allows describing circuits as Haskell functions and mealy machines, and bundles signals for simulation and compilation to VHDL. Example code was shown for a seven segment display driven by a counter circuit. The workflow allows behavioral testing in Haskell and generation of VHDL for synthesis, without necessarily being less efficient than hand-coding in VHDL.
The document contains code snippets in C++ for graphics programs to draw various shapes and perform transformations like translation, rotation, and scaling using Turbo C++. It includes programs to draw a line, rotate a line, scale a line, display text horizontally and vertically, draw a house, fish, and man cartoon. Each code example contains functions for initialization, input, drawing objects using lines, circles, rectangles, and outputting text.
This project report describes a treadmill simulation project using an 8052 microcontroller. The hardware components included an 8052 microcontroller, LCD display, numeric keypad, DC motor, and other components. The code was written to control the keypad, LCD display, motor and calculate calories burned based on speed, time, weight and gender of the user. The project was simulated using Proteus and results matched the expected functionality.
This document includes header files and code for interfacing with GPS, compass, and SD card components. It initializes these devices and logs GPS data including latitude, longitude, and fix age to an SD card file. It also calculates distance between the current GPS position and predefined waypoints. The main loop acquires new GPS data every 250ms and prints it to the serial monitor if available.
1. Use nonatomic properties for primitive types like floats to avoid locking.
2. Use CCArray instead of NSMutableArray for better performance in cocos2d. Iterate arrays using CC_ARRAY_FOREACH.
3. Use index access instead of indexOfObject to improve performance of lookups in for loops.
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014PyData
Pythran is a an ahead of time compiler that turns modules written in a large subset of Python into C++ meta-programs that can be compiled into efficient native modules. It targets mainly compute intensive part of the code, hence it comes as no surprise that it focuses on scientific applications that makes extensive use of Numpy. Under the hood, Pythran inter-procedurally analyses the program and performs high level optimizations and parallel code generation. Parallelism can be found implicitly in Python intrinsics or Numpy operations, or explicitly specified by the programmer using OpenMP directives directly in the Python source code. Either way, the input code remains fully compatible with the Python interpreter. While the idea is similar to Parakeet or Numba, the approach differs significantly: the code generation is not performed at runtime but offline. Pythran generates C++11 heavily templated code that makes use of the NT2 meta-programming library and relies on any standard-compliant compiler to generate the binary code. We propose to walk through some examples and benchmarks, exposing the current state of what Pythran provides as well as the limit of the approach.
Bartosz Milewski, “Re-discovering Monads in C++”Platonov Sergey
Once you know what a monad is, you start seeing them everywhere. The std::future library of C++11 was an example of an incomplete design, which stopped short of recognizing the monadic nature of futures. This is now being remedied in C++17, and there are new library additions, like std::expected and the range library, that are much more monad-conscious. I’ll explain what a monad is using copious C++ examples.
The document discusses various techniques for improving OpenGL application performance, including using vertex buffer objects (VBOs) and vertex array objects (VAOs) to store vertex data in graphics memory. It provides an example of creating a cube using VBOs and VAOs to initialize vertex position and color data and load it into a VBO. Display lists are described as allowing geometry to be defined once and executed multiple times to improve performance for redrawing the same geometry. Frustum culling and scissoring are introduced as clipping techniques. General memory management techniques like avoiding frequent memory allocations in loops are also covered.
The document provides source code for generating and manipulating computer graphics using various algorithms. It includes algorithms for drawing lines, circles and curves, as well as algorithms for translating, rotating, and scaling two-dimensional and three-dimensional objects. The source code is written in C/C++ and uses graphics libraries to output the results. Various input parameters are taken from the user and output is displayed to demonstrate the algorithms.
Exploring Color Spaces with Gesture Tracking and Smart Bulbs (Distill 2014)Daniel Luxemburg
The document discusses exploring different color spaces like RGB, HSL, and HSV by tracking hand gestures with a Leap Motion controller and controlling LIFX smart bulbs. Code examples are provided in Ruby and JavaScript to discover LIFX bulbs, map hand position data to color values, and set the bulb colors. The goal is to enable new ways of interacting with technology through gesture control and different representations of color.
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"OdessaJS Conf
Node.js uses the V8 JavaScript engine and the libuv library. V8 compiles JavaScript to machine code for high performance, while libuv provides asynchronous I/O capabilities. Node.js initializes V8, wraps libuv, and provides a module system to load code, with modules defined as functions that export values. Native modules can extend Node.js using NAN or the newer N-API for direct access to V8 from C/C++ code.
This document provides an overview of basic data structures concepts. It discusses bits and data types, different numeric representations like binary and decimal. It introduces common data types used in programming like integers and floats. It also covers abstract data types and provides examples like stacks, queues and lists. The document describes iterative and recursive algorithms for problems like factorial calculation, binary search and the Towers of Hanoi. It analyzes the time complexity of algorithms like selection sort.
The document discusses the implementation of a binary search tree (BST) using both recursive and non-recursive traversal methods. It defines a BST node structure with left and right child pointers. Functions are included to insert nodes, perform inorder, preorder and postorder traversals recursively and non-recursively using stacks. Main inserts sample nodes into the tree and calls the various traversal functions to output the node values in the specified orders.
The document summarizes AA-sort, a sorting algorithm optimized for SIMD and multicore processors. AA-sort works by first sorting blocks of data in parallel using vectorized combsort. It then merges the sorted blocks together. Key steps include sorting 4 elements within each SIMD register, transposing the registers, and performing a vectorized version of combsort without conditional branches. The document provides pseudocode for these steps.
Translating Classic Arcade Games to JavaScriptnorbert_kehrer
This document discusses translating classic arcade games like Asteroids from the 6502 processor to JavaScript. It begins by explaining emulation versus recompilation approaches. It then describes translating the 6502 assembly code to JavaScript by representing registers as variables and memory as arrays. Challenges like conditional branches are addressed. Optimization techniques like redundant flag calculation elimination are discussed, linking the translation to compiler theory topics like liveness analysis. The goal is a browser-playable version of Asteroids that demonstrates translating a real-world 6502 application to JavaScript.
This document provides C code solutions to interface four 7-segment displays on an ARM7 microcontroller and display counts from 0000 to 9999. The code defines arrays to store the digit values for the displays and uses conditions to extract the digits from the count value to display on the individual segments. Delay functions are used to control the timing of digit updates on the displays.
This document discusses using multithreading in Java with LEJOS to control a line following robot. It presents the original single-threaded code and then improves it using two threads - one for line following and one for obstacle detection. The main program starts each thread and uses a DataExchange class to allow the threads to communicate and coordinate the robot's behavior. When no obstacles are detected, the line following thread controls the motors to follow a black line. When an obstacle is detected within 25cm, the obstacle detection thread stops the line following behavior.
The document discusses different approaches to implementing GPU-like programming on CPUs using C++AMP. It covers using setjmp/longjmp to implement coroutines for "fake threading", using ucontext for coroutine context switching, and how to pass lambda functions and non-integer arguments to makecontext. Implementing barriers on CPUs requires synchronizing threads with an atomic counter instead of GPU shared memory. Overall, the document shows it is possible to run GPU-like programming models on CPUs by simulating the GPU programming model using language features for coroutines and threading.
This document contains C++ code to find roots of equations using the bisection method. It includes 4 questions:
1) Finds the root of x3 – 4x – 8.95 = 0 between 2 and 3 to 3 decimal places.
2) Finds the root of ex – 3x = 0 using bisection up to a specified number of iterations.
3) Defines a bisection function to find the root of f(x) = x6 – x – 1 = 0 within 0.001 accuracy.
4) Defines a bisection function to find the smallest positive root of a cubic equation ax3+bx2+cx+d=0 within an error tolerance of 10-6.
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"OdessaJS Conf
This document introduces MetaSync, a library for asynchronous programming in JavaScript. It discusses current asynchronous patterns like callbacks, promises, and async/await and their limitations. MetaSync aims to address these issues through function composition for asynchronous I/O, specific asynchronous abstractions, and a short, expressive syntax. It allows composing asynchronous functions sequentially or in parallel and includes tools like collectors, throttling, and queues to manage asynchronous data and operations.
On using Haskell DSL - CLaSH, to implement a simple digital stopwatch on FPGAmjgajda
This document summarizes a Haskell.SG MeetUp presentation about using the ClaSH compiler plugin to compile Haskell code describing digital logic circuits into VHDL for implementation on FPGAs. The presentation introduced basic digital logic concepts like gates, clocks, registers and three-state logic. It described how ClaSH allows describing circuits as Haskell functions and mealy machines, and bundles signals for simulation and compilation to VHDL. Example code was shown for a seven segment display driven by a counter circuit. The workflow allows behavioral testing in Haskell and generation of VHDL for synthesis, without necessarily being less efficient than hand-coding in VHDL.
The document contains code snippets in C++ for graphics programs to draw various shapes and perform transformations like translation, rotation, and scaling using Turbo C++. It includes programs to draw a line, rotate a line, scale a line, display text horizontally and vertically, draw a house, fish, and man cartoon. Each code example contains functions for initialization, input, drawing objects using lines, circles, rectangles, and outputting text.
This project report describes a treadmill simulation project using an 8052 microcontroller. The hardware components included an 8052 microcontroller, LCD display, numeric keypad, DC motor, and other components. The code was written to control the keypad, LCD display, motor and calculate calories burned based on speed, time, weight and gender of the user. The project was simulated using Proteus and results matched the expected functionality.
I have written the code but cannot complete the assignment please help.pdfshreeaadithyaacellso
I have written the code but cannot complete the assignment please help me to complete.
Please don't just copy other s answers as your own.
// Insertion sort
/*
#include <ctime>
#include <iostream>
using namespace std;
void insertionSort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
// Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current
position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
int main() {
int n;
cout << "Enter the size of the array: ";
cin >> n;
int arr[n];
cout << "Enter the elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int num = sizeof(arr) / sizeof(arr[0]);
clock_t start, end;
double timetaken;
start = clock();
insertionSort(arr, num);
end = clock();
cout << "Sorted array: \n";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
timetaken = ((double) (end - start)) / CLOCKS_PER_SEC;
cout << "Time taken : " << fixed << timetaken << "s" << endl;
return 0;
}
*/
// Shell Sort
/*
#include <ctime>
#include <iostream>
using namespace std;
int shellSort(int arr[], int n) {
for (int gap = n/2; gap > 0; gap /= 2) {
for (int i = gap; i < n; i += 1) {
int temp = arr[i];
int j;
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)
arr[j] = arr[j - gap];
arr[j] = temp;
}
}
return 0;
}
void printArray(int arr[], int n) {
for (int i=0; i<n; i++)
cout << arr[i] << " ";
}
int main() {
int n;
cout << "Enter the size of the array: ";
cin >> n;
int arr[n];
cout << "Enter the elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int num = sizeof(arr) / sizeof(arr[0]);
clock_t start, end;
double timetaken;
start = clock();
shellSort(arr, num);
end = clock();
cout << "\nArray after sorting: \n";
printArray(arr, n);
cout << endl;
timetaken = (double)(end - start) / CLOCKS_PER_SEC;
cout << "Time taken : " << fixed << timetaken << "s" << endl;
return 0;
}
*/
// MergeSort
/*
#include <ctime>
#include <iostream>
using namespace std;
void merge(int arr[], int l, int m, int r) {
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r) {
if (l < r) {
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
int main() {
int n;
cout << "Enter the size of the array: ";
cin >> n;
int arr[n];
cout << "Enter the elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int arr_size = sizeof(arr) / sizeof(arr[0]);
clock_t start;
clock_t end;
double timetaken;
start = clock();
mergeSort(arr, 0, arr_size - 1);
end = clock();
timetaken = (double)(end - start) / CLOCKS_PER_SEC;
.
This C program implements a snake game using graphics. It initializes a linked list to represent the snake and randomly generates food on the screen. It uses functions to check for collisions with food/body, move the snake according to key presses, and draw the snake/food each frame. The main game loop runs continuously, checking for input, calling functions to update the snake's position and check for collisions, drawing the updated scene, and exiting if the snake collides with itself or the edge of the screen.
The document defines constants for controlling 3 stepper motors using Arduino. It includes functions for initializing pin modes, controlling motor speed and direction, and stepping each motor. The main loop calls the motor functions to run the motors in sequences, and also controls a servo motor.
Being a slow interpreter, Python may drive a system to deliver utmost speed if some guidelines are followed. The key is to treat programming languages as syntactic sugar to the machine code. It expedites the workflow of timing, iterative design, automatic testing, optimization, and realize an HPC system balancing the time to market and quality of code.
Speed is the king. 10x productive developers change business. So does 10x faster code. Python is 100x slower than C++ but it only matters when you really use Python to implement number-crunching algorithms. We should not do that, and instead go directly with C++ for speed. It calls for strict disciplines of software engineering and code quality, but it should be noted that here the quality is defined by the runtime and the time to market.
The presentation focuses on the Python side of the development workflow. It is made possible by confining C++ in architecture defined by the Python code, which realizes most of the software engineering. The room for writing fast C++ code is provided by pybind11 and careful design of typed data objects. The data objects hold memory buffers exposed to Python as numpy ndarrays for direct access for speed.
This document defines constants for pin assignments and includes the Servo library. It controls 3 stepper motors using microstepping to move specified steps in a given direction at a specified speed. A servo motor is also controlled to two positions. The main loop calls functions to operate each motor independently in sequences, such as moving one motor forward and another backward simultaneously.
The document describes an experiment implementing a static scheduler for 4 periodic tasks (T1-T4) on a Linux machine. The tasks have different periods and execution times. Code is provided to define each task function, which performs a calculation and prints execution time. The main function implements the static scheduling algorithm, running the tasks in a loop over a hyperperiod of 20 seconds. It measures and prints the total execution time.
This document contains programs written in C++ to perform encryption and decryption using Caesar cipher, Vigenere cipher, and Playfair cipher. It includes the code for encrypting and decrypting text using Caesar cipher. It also includes code for encrypting and decrypting text using Vigenere cipher's autokey method. There is incomplete code provided for Playfair cipher that distributes the alphabet and key into a 5x5 matrix but does not include the encryption logic.
This document summarizes common C programming concepts including data types, arrays, functions, conditionals, loops, and the main function. It discusses declaring variables of basic data types like int, float, and double. It also covers one-dimensional and two-dimensional arrays, defining functions with different return types, and using if/else, switch, for, while loops for control flow. The main() function is described as the required entry point for all C programs.
write the TODO part of the program.docxannetnash8266
write the //TODO part of the program:
/***************************************************************************
* scramble.c
*
* Problem Set 3
*
* Implements Scramble with CS50.
*
* Usage: scramble [#]
*
* where # is an optional grid number.
***************************************************************************/
#include [removed]
#include [removed]
#include [removed]
#include [removed]
#include [removed]
#include [removed]
// duration of a game in seconds
#define DURATION 30
// grid's dimensions
#define DIMENSION 4
// maximum number of words in any dictionary
#define WORDS 172806
// maximum number of letters in any word
#define LETTERS 29
// default dictionary
// http://www.becomeawordgameexpert.com/wordlists.htm
#define DICTIONARY "words"
// for logging
FILE* log;
// grid
char grid[DIMENSION][DIMENSION];
// flags with which we can mark grid's letters while searching for words
bool marks[DIMENSION][DIMENSION];
// defines a word as having an array of letters plus a flag
// indicating whether word has been found on grid
typedef struct
{
bool found;
char letters[LETTERS + 1];
}
word;
// defines a dictionary as having a size and an array of words
struct
{
int size;
word words[WORDS];
}
dictionary;
// prototypes
void clear(void);
bool crawl(string letters, int x, int y);
void draw(void);
bool find(string s);
void initialize(void);
bool load(string s);
bool lookup(string s);
void scramble(void);
// This is Scramble.
int main(int argc, string argv[])
{
// ensure proper usage
if (argc > 2)
{
printf("Usage: %s [#]\n", basename(argv[0]));
return 1;
}
// seed pseudorandom number generator
if (argc == 2)
{
int seed = atoi(argv[1]);
if (seed <= 0)
{
printf("Invalid grid.\n");
return 1;
}
srand(seed);
}
else
srand(time(NULL));
// determine path to dictionary
string directory = dirname(argv[0]);
char path[strlen(directory) + 1 + strlen(DICTIONARY) + 1];
sprintf(path, "%s/%s", directory, DICTIONARY);
// load dictionary
if (!load(path))
{
printf("Could not open dictionary.\n");
return 1;
}
// initialize the grid
initialize();
// initialize user's score
int score = 0;
// calculate time of game's end
int end = time(NULL) + DURATION;
// open log
log = fopen("log.txt", "w");
if (log == NULL)
{
printf("Could not open log.\n");
return 1;
}
// accept words until timer expires
while (true)
{
// clear the screen
clear();
// draw the current state of the grid
draw();
// log board
for (int row = 0; row < DIMENSION; row++)
{
for (int col = 0; col [removed]= end)
.
A scrupulous code review - 15 bugs in C++ codePVS-Studio LLC
A close look at 15 problems one can find when reviewing C++ code.
Offers code examples.
Covers indexed loops, tainted data, copy and paste errors, problems with comparisons, exceptions, etc.
You can use static code analysis tools to make code review easier. Code analyzers find errors and potential vulnerabilities in code, while saving the developers' time and the companies' money.
Manual code review is expensive - a group of programmers get together regularly to review the code.
One can run static analysis tools regularly to find mistakes and vulnerabilities early.
The document discusses various concepts related to arrays in C programming language including initializing arrays, accessing array elements using subscripts, storage of arrays in memory, bounds checking for arrays, and different sorting algorithms like selection sort, bubble sort, and quick sort that can be applied to arrays. It provides code examples and explanations for initializing, accessing, and sorting integer arrays.
The IoT Academy IoT Training Arduino Part 3 programmingThe IOT Academy
This document provides an overview of basic Arduino code structure and programming concepts. It explains that Arduino programs have two main sections - setup() and loop(). Setup() is used to initialize inputs and outputs, and loop() contains the repeating code. It also covers digital input/output functions, variables, conditional statements, boolean logic, and interrupts. Examples are provided for blinking LEDs, reading sensors, and creating simple programs.
The purpose of this C++ programming project is to allow the student .pdfRahul04August
The purpose of this C++ programming project is to allow the student to perform parallel array
and multidimensional array processing. The logic for string and Cstring has already been
completed, so the assignment can be started before we actually cover string and Cstring in detail.
This program has the following three menu options:
Solution
/*
This program uses simple arrays, multidimensional arrays, cstrings, strings, and files.
It allows a payroll clerk to choose an option from a menu. The choices are:
A: List the Payroll Information by Employee Name
B: Search Payroll Information by Employee Name
X: Exit the Payroll Information Module
The following items for each employee are saved in the file p10.txt:
Employee ID (1000 - 9999)
Last Name (15 characters)
First Name (15 characters)
Rate (5.00 - 10.00)
Hours W1,W2,W3,W4 (0-60)
*/
#include // file processing
#include // cin and cout
#include // toupper
#include // setw
#include // cstring functions strlen, strcmp, strcpy stored in string.h
#include // string class
#define stricmp strcasecmp
#define strnicmp strncasecmp
using namespace std;
//Disable warning messages C4267 C4996.
//To see the warnings, comment out the following line.
//#pragma warning( disable : 4267 4996)
//Warning C4267: coversion from size_t to int, possible lost of data
//size_t is a data type defined in and is an unsigned integer.
//The function strlen returns a value of the type size_t, but in
//searchByName we assign the returned value to an int.
//We could also declare the variable as size_t instead of int.
// size_t stringLength;
//Warning C4996: strnicmp strcpy, stricmp was declared deprecated, means
//the compiler encountered a function that was marked with deprecated.
//The deprecated function may no longer be supported in a future release.
//Global Constants
//When using to declare arrays, must be defined with const modifier
const int ARRAY_SIZE = 20, HOURS_SIZE = 4, NAME_SIZE = 16;
//Declare arrays as global so we don\'t have to pass the arrays to each function.
//Normally we wouldn\'t declare variables that change values a global.
int employeeId[ARRAY_SIZE];
string firstName[ARRAY_SIZE];
char lastName[ARRAY_SIZE][NAME_SIZE];
double rate[ARRAY_SIZE];
int hours[ARRAY_SIZE][HOURS_SIZE];
int numberOfEmps; //count of how many employees were loaded into arrays
int sumHours[ARRAY_SIZE] = {0}; //initialize arrays to zero by providing a
double avgHours[ARRAY_SIZE] = {0}; //value for the first element in the array
//Function Prototypes
void loadArray( );
void sumAndComputeAvgHours( );
void listByName( );
void searchByName( );
void sortByName( );
void swapValues(int i, int minIndex);
void listEmployees( );
void listEmployeesHeadings( );
void listEmployeesDetails(int i);
void listEmployeesTotals( );
void displayContinuePrompt( );
//Program starts here
int main()
{
//Declare and initialize local main variables
char choice; //menu option
//Load the arrays with data
loadArray();
//Sum and compute the average hours
sumAndComputeAv.
Similar to Senior design project code for PPG (20)
Advanced control scheme of doubly fed induction generator for wind turbine us...IJECEIAES
This paper describes a speed control device for generating electrical energy on an electricity network based on the doubly fed induction generator (DFIG) used for wind power conversion systems. At first, a double-fed induction generator model was constructed. A control law is formulated to govern the flow of energy between the stator of a DFIG and the energy network using three types of controllers: proportional integral (PI), sliding mode controller (SMC) and second order sliding mode controller (SOSMC). Their different results in terms of power reference tracking, reaction to unexpected speed fluctuations, sensitivity to perturbations, and resilience against machine parameter alterations are compared. MATLAB/Simulink was used to conduct the simulations for the preceding study. Multiple simulations have shown very satisfying results, and the investigations demonstrate the efficacy and power-enhancing capabilities of the suggested control system.
International Conference on NLP, Artificial Intelligence, Machine Learning an...gerogepatton
International Conference on NLP, Artificial Intelligence, Machine Learning and Applications (NLAIM 2024) offers a premier global platform for exchanging insights and findings in the theory, methodology, and applications of NLP, Artificial Intelligence, Machine Learning, and their applications. The conference seeks substantial contributions across all key domains of NLP, Artificial Intelligence, Machine Learning, and their practical applications, aiming to foster both theoretical advancements and real-world implementations. With a focus on facilitating collaboration between researchers and practitioners from academia and industry, the conference serves as a nexus for sharing the latest developments in the field.
Understanding Inductive Bias in Machine LearningSUTEJAS
This presentation explores the concept of inductive bias in machine learning. It explains how algorithms come with built-in assumptions and preferences that guide the learning process. You'll learn about the different types of inductive bias and how they can impact the performance and generalizability of machine learning models.
The presentation also covers the positive and negative aspects of inductive bias, along with strategies for mitigating potential drawbacks. We'll explore examples of how bias manifests in algorithms like neural networks and decision trees.
By understanding inductive bias, you can gain valuable insights into how machine learning models work and make informed decisions when building and deploying them.
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...University of Maribor
Slides from talk presenting:
Aleš Zamuda: Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapter and Networking.
Presentation at IcETRAN 2024 session:
"Inter-Society Networking Panel GRSS/MTT-S/CIS
Panel Session: Promoting Connection and Cooperation"
IEEE Slovenia GRSS
IEEE Serbia and Montenegro MTT-S
IEEE Slovenia CIS
11TH INTERNATIONAL CONFERENCE ON ELECTRICAL, ELECTRONIC AND COMPUTING ENGINEERING
3-6 June 2024, Niš, Serbia
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsVictor Morales
K8sGPT is a tool that analyzes and diagnoses Kubernetes clusters. This presentation was used to share the requirements and dependencies to deploy K8sGPT in a local environment.
We have compiled the most important slides from each speaker's presentation. This year’s compilation, available for free, captures the key insights and contributions shared during the DfMAy 2024 conference.
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTjpsjournal1
The rivalry between prominent international actors for dominance over Central Asia's hydrocarbon
reserves and the ancient silk trade route, along with China's diplomatic endeavours in the area, has been
referred to as the "New Great Game." This research centres on the power struggle, considering
geopolitical, geostrategic, and geoeconomic variables. Topics including trade, political hegemony, oil
politics, and conventional and nontraditional security are all explored and explained by the researcher.
Using Mackinder's Heartland, Spykman Rimland, and Hegemonic Stability theories, examines China's role
in Central Asia. This study adheres to the empirical epistemological method and has taken care of
objectivity. This study analyze primary and secondary research documents critically to elaborate role of
china’s geo economic outreach in central Asian countries and its future prospect. China is thriving in trade,
pipeline politics, and winning states, according to this study, thanks to important instruments like the
Shanghai Cooperation Organisation and the Belt and Road Economic Initiative. According to this study,
China is seeing significant success in commerce, pipeline politics, and gaining influence on other
governments. This success may be attributed to the effective utilisation of key tools such as the Shanghai
Cooperation Organisation and the Belt and Road Economic Initiative.
A review on techniques and modelling methodologies used for checking electrom...nooriasukmaningtyas
The proper function of the integrated circuit (IC) in an inhibiting electromagnetic environment has always been a serious concern throughout the decades of revolution in the world of electronics, from disjunct devices to today’s integrated circuit technology, where billions of transistors are combined on a single chip. The automotive industry and smart vehicles in particular, are confronting design issues such as being prone to electromagnetic interference (EMI). Electronic control devices calculate incorrect outputs because of EMI and sensors give misleading values which can prove fatal in case of automotives. In this paper, the authors have non exhaustively tried to review research work concerned with the investigation of EMI in ICs and prediction of this EMI using various modelling methodologies and measurement setups.
Introduction- e - waste – definition - sources of e-waste– hazardous substances in e-waste - effects of e-waste on environment and human health- need for e-waste management– e-waste handling rules - waste minimization techniques for managing e-waste – recycling of e-waste - disposal treatment methods of e- waste – mechanism of extraction of precious metal from leaching solution-global Scenario of E-waste – E-waste in India- case studies.
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMSIJNSA Journal
The smart irrigation system represents an innovative approach to optimize water usage in agricultural and landscaping practices. The integration of cutting-edge technologies, including sensors, actuators, and data analysis, empowers this system to provide accurate monitoring and control of irrigation processes by leveraging real-time environmental conditions. The main objective of a smart irrigation system is to optimize water efficiency, minimize expenses, and foster the adoption of sustainable water management methods. This paper conducts a systematic risk assessment by exploring the key components/assets and their functionalities in the smart irrigation system. The crucial role of sensors in gathering data on soil moisture, weather patterns, and plant well-being is emphasized in this system. These sensors enable intelligent decision-making in irrigation scheduling and water distribution, leading to enhanced water efficiency and sustainable water management practices. Actuators enable automated control of irrigation devices, ensuring precise and targeted water delivery to plants. Additionally, the paper addresses the potential threat and vulnerabilities associated with smart irrigation systems. It discusses limitations of the system, such as power constraints and computational capabilities, and calculates the potential security risks. The paper suggests possible risk treatment methods for effective secure system operation. In conclusion, the paper emphasizes the significant benefits of implementing smart irrigation systems, including improved water conservation, increased crop yield, and reduced environmental impact. Additionally, based on the security analysis conducted, the paper recommends the implementation of countermeasures and security approaches to address vulnerabilities and ensure the integrity and reliability of the system. By incorporating these measures, smart irrigation technology can revolutionize water management practices in agriculture, promoting sustainability, resource efficiency, and safeguarding against potential security threats.
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
Senior design project code for PPG
1. #include <TFT.h> // Arduino LCD library
#include <SPI.h>
// SPI pin definition for the Mega. Check the SPI page on Arduino website for
more info
#define cs 10
#define dc 9
#define rst 8
#define sda 51
#define scl 52
TFT screen = TFT(cs, dc, rst);// create an instance of the screen library
unsigned long peaktArr[11], pAndt[2][3]; //peaktArr stores the peak values from
pAndt; pAndt stores the values from the sensor which are compared to one another
to determine a peak
float tdiff[10];//array to store time difference between consecutive time
stamps
int i = 0;
int j = 0;
int k = 0;
float inst_f = 0;
int p = 0;
int a = 0;
unsigned long calb;
int xPos = 0;//initial value (position) of the cursor that draws the waveform
void setup(){//the entire code in this loop will only happen 1 time
screen.begin();//initializing the screen
screen.setTextSize(2);//increasing text size 10X
screen.background(0, 0, 255);
unsigned long delayTime = millis();//millis() stores the amount of time in
milliseconds that has passed since it was introduced into the program. This
value is then passed into the variable delayTime
while(millis() - delayTime <= 3000){ // delayTime has a set value and will not
change and the program within the the while loop will run as long the difference
between millis() and delayTime is less than 3000 milliseconds or 3 seconds
screen.setCursor(0,0);///the 1st value in brackets sets the distance from the
left edge of the screen, and the 2nd value sets the distance from the top edge
of the screen
screen.print("Welcome To");
screen.setCursor(0,25);
screen.print("Chelsea's");
screen.setCursor(0,50);
screen.print("Heart Rate");
screen.setCursor(0,75);
screen.print("Device");
}
screen.background(0,0,255);//the 1st value is blue intensity, the 2nd is green
intensity and the 3rd is red intensity. this line makes the background color red
delayTime = millis();
while(millis() - delayTime <= 3000){
screen.setCursor(0,0);
screen.print("Place Finger");
screen.setCursor(0,25);
screen.print("On Sensor");
}
screen.background(0,0,255);
screen.setCursor(0,50);
screen.print("Calibrating");
for(i = 0; i < 3; i++){//read and store 3 values at a time in pAndt
unsigned long delayTime = millis();
pAndt[0][i] = analogRead(A0);//1st row of pAndt stores the sensor values
pAndt[1][i] = millis();// 2nd row of pAndt stores the time stamp of the
sensor values
while (millis() - delayTime <=200){//wait 200 ms before reading the next
2. sensor values. this means we read 5 values every second
}
}
for(i = 1; i < 2; i++){
if(pAndt[0][i]>pAndt[0][i-1] && pAndt[0][i]>pAndt[0][i+1]){ //compare the
3 values in pAndt to determine a peak
peaktArr[0] = pAndt[1][i];// store the value of i that satisfies the
peak condition
}
}
while(j<11){//the entire code within the while loop repeats until we get 11
values in peaktArr
//replace the values of the 1st column with those of the 2nd column
pAndt[0][0] = pAndt[0][1];//replace the values in row 1
pAndt[1][0] = pAndt[1][1];//replace the values in row 2
//replace the values of the 2nd column with those of the 3rd column
pAndt[0][1] = pAndt[0][2];//replace the values in row 1
pAndt[1][1] = pAndt[1][2];//replace the values in row 2
unsigned long delayTime = millis();//
for(i = 2; i < 3; i++){//read and store 1 value in the 3rd column of pAndt
pAndt[0][i] = analogRead(A0);//1st row of pAndt stores the sensor values
pAndt[1][i] = millis();// 2nd row of pAndt stores the time stamp of the
sensor values
while (millis() - delayTime <=200){//delay in ms before reading the next
value
}
}
for(i = 1; i < 2; i++){
if(pAndt[0][i]>pAndt[0][i-1] && pAndt[0][i]>pAndt[0][i+1]){ //compare the
3 values in pAndt to determine a peak
peaktArr[j++] = pAndt[1][i];// store the value of i that satisfies the
peak condition
}
}
}
for(i = 0; i < 10; i++){
tdiff[k++] = (((float)peaktArr[i+1] - (float)peaktArr[i])/1000);//change
the time values from unsigned long to float, take the difference between
consecutive time values, and convert the result to time in seconds
}
for(i = 0; i < 10; i++){
inst_f = inst_f + (1/tdiff[i]);//convert the time differences to
frequencies and take their sum
}
screen.background(0,0,255);
screen.setCursor(0,0);
screen.print("Heart rate ");
screen.setCursor(0,20);
screen.print((inst_f/10)*60);
screen.setCursor(75,20);
screen.println(" bpm");
while(xPos<=160){
int sensor = analogRead(A0);
int graphHeight = map(sensor,0,682,5,screen.height()/1.5);//map assigns
corresponding values between analog and digital. 0 is the lowest digital
reading,682 is the highest digital reading,5 is the position at which the lowest
reading will appear and screen.height()/1.5 is the position at which the highest
reading will appear
3. screen.stroke(255,255,255);
screen.line(xPos, (screen.height() - graphHeight), xPos, screen.height() -
graphHeight+3); //screen.height() - graphHeight + 5 affects the thickness of the
line. The bigger the number you add to screen.height() - graphHeight is, the
thicker the line will be
xPos++;
delayTime = millis();
while(millis() - delayTime<=25){//rate at which points are displayed on
screen to plot waveform
}
}
void loop(){
int xPos = 0;
float inst_f = 0;
for(i = 2; i<11; i++){
peaktArr[i-2] = peaktArr[i];//remove the 1st 2 values from the peaktArr array
and shift all the values until the last 2 "spots" in the array are empty
}
j = 9;//start filling peaktArr from index 9 (10th position)
for(i = 1; i<10; i++){
tdiff[i-1] = tdiff[i];//remove the earliest time difference that was
calculated and shift the other values until the last "spot" in the array is
empty
}
while(j<11){
pAndt[0][0] = pAndt[0][1];
pAndt[1][0] = pAndt[1][1];
pAndt[0][1] = pAndt[0][2];
pAndt[1][1] = pAndt[1][2];
unsigned long delayTime = millis();//
for(i = 2; i < 3; i++){
pAndt[0][i] = analogRead(A0);
pAndt[1][i] = millis();
while (millis() - delayTime <=200){
}
}
for(i = 1; i < 2; i++){
if(pAndt[0][i]>pAndt[0][i-1] && pAndt[0][i]>pAndt[0][i+1] /*&& pAndt[0][i]
>= 0.3*hp*/){ //compare the 3 values in pAndt to determine a peak
peaktArr[j++] = pAndt[1][i];// store the value of i that satisfies the
peak condition, and do the comparison above until j is 10
}
}
}
tdiff[9] = (((float)peaktArr[10] - (float)peaktArr[9])/1000);
for(i = 0; i < 10; i++){
inst_f = inst_f + (1/tdiff[i]);
}
screen.background(0,0,255);
screen.setCursor(0,0);
screen.print("Heart rate ");
screen.setCursor(0,20);
screen.print((inst_f/10)*60);
screen.setCursor(75,20);
screen.println(" bpm");
while(xPos<=160){
int sensor = analogRead(A0);
int graphHeight = map(sensor,0,682,5,screen.height()/1.5);
screen.stroke(255,255,255);
4. screen.line(xPos, (screen.height() - graphHeight), xPos, screen.height() -
graphHeight+3); //screen.height() - graphHeight + 5 affects the thickness of the
line. The bigger the number you add to screen.height() - graphHeight is, the
thicker the line will be
xPos++;
unsigned long delayTime = millis();
while(millis() - delayTime<=25){
}
}
screen.background(0,0,255);
screen.print("Calculating..");
unsigned long delayTime = millis();
while (millis()- delayTime <= 5000){
}
}