C++ Classes
In C++, classes are the building blocks of object-oriented programming. A class is similar to a structure, except that a class is designed to include function members, as well as data members. A well-designed class can be used as easily as a predefined data type. Instances of a class are called objects. We have used predefined classes and objects in the previous discussion. For example, we used the cin object and the cout object to perform standard input and output operations. These objects are also called functions, including precision and setf.
Defining a Class Data Type
A class definition consists of two parts: a class declaration and a class implementation.
Class declaration: the name of the class is specified using the keyword class. The body of the class declaration consists of type declaration statements for the data members and function prototypes for the function members.
class sample
{
public:
void print();
double variable();
};
Suppose we want to define a data type to represent a data point that is represented in rectangular coordinates; thus, the data type is represented by an x-coordinate and a y-coordinate, as shown below. When designing a class type, we need to consider the data members that are required to represent the new data type, as well as the operations that we would like to define for the data type.
The class design includes function members to implement the desired operations. Consider the class declaration that we present for the xy_coordinate class, which consists of
two data members to define the point and two member functions that operate on the coordinates to determine the radius r and the angle q, as at right. We will add additional member functions to the design of the xy_coordinate class later in this section. The class declaration, is typically stored in a header file, as shown in the following code:
// These statements define a class for xy-coordinates.
// This declaration is stored in xy_coordinate.h.
#include <iostream>
#include <cmath>
using namespace std;
class xy_coordinate
{
// Declare function prototypes for public members.
public:
void input();
void print();
double radius();
double angle();
private:
// Declare private data members.
double x, y;
};
The xy_coordinate class has two data members and four function members. The keywords public and private are used to control access to the members of the class.
PUBLIC: Members that are specified as public members may be referenced anywhere in the user program.
PRIVATE: Members that are specified as private members may only be referenced by member functions of the xy_coordinate class. This restricted access is known as information hiding. If modifications are made to the data representation of a class, only the member functions need to be modified; no change to the user program is required. Any private member functions can only be called by other member functions. These private member functions are often referred to as helper functions because they are designed to help the other member functions.
CLASS IMPLEMENTATION consists of all the member function definitions. When defining a member function, the scope resolution operator (::) is used in the function definition. This operator is placed between the class name and the function name to specify that the function is a member of the class. When writing a member function definition, first specify the type of value being returned by the function. The class name, the scope resolution operator, the name of the function, and the parameter list will follow. Recall that all member functions have direct access to the data members, so the data members do not appear in the parameter list. Helper functions can also be called directly by a member function. A class implementation can also be stored in a separate file.
// These statements define implementation of an
// xy_coordinate class. They are stored in xy-coordinate.h.
// This function reads the xy coordinates from the keyboard.
void xy_coordinate::input()
{
cin >> x >> y;
}
// This function prints the xy coordinates to the screen.
void xy_coordinate::print()
{
cout << "(" << x << "," << y << ")" << "\n";
}
// This function computes the radius.
double xy_coordinate::radius()
{
return sqrt(x*x + y*y);
}
// This function computes the angle in radians.
double xy_coordinate::angle()
{
// Compute angle of polar form.
double z, pi=3.141593;
if (x >= 0)
z = atan(y/x);
if (x<0 && y>0)
z = atan(y/x) + pi;
if (x<0 && y<=0)
z = atan(y/x) - pi;
if (x==0 && y==0)
z = 0;
return z;
}
We now present a program to test this new data type.
// This program demonstrates the use of
// the xy_coordinate class and its functions.
#include <iostream>
#include <cmath>
#include "xy_coordinate.h"
using namespace std;
int main(void)
{
// Declare and initialize variables.
xy_coordinate pt1;
// Read input point.
cout << "Enter x and y coordinates:" << endl;
pt1.input();
// Print coordinate in xy form and polar form.
cout.setf(ios::fixed);
cout.precision(2);
cout << "Coordinate in xy form:" << endl;
pt1.print()
cout << "Coordinate in polar form:" << endl;
cout << "magnitude: " << pt1.radius() << endl;
cout << "phase (in degrees)" << pt1.angle()*180/3.141593 << endl;
// Exit program.
return 0;
}
At this point we will have you install the DEV C++ compiler and walk you through getting this program working with the compiler.
To execute this program, you need to be sure that the xy_coordinate header file and the xy_coordinate implementation file are accessible to the compiler, along with the program file. This separation of the components allows us to build our own libraries for programmer- defined classes. These libraries can be used by many application programs in the same way that the standard libraries, such as iostream are used. The application program must include the declarations file and be linked to the implementation file. Using these files, we can now test the program. Here is a sample output from the program:
Enter x and y coordinates:
4 4
Coordinate in xy form:
(4.00,4.00)
Coordinate in polar form:
magnitude: 5.66
phase (in degrees): 45.00
Constructor Functions
When we define a variable, we often want to assign an initial value to the variable, as in
double sum=0;
If we do not initialize a variable at the time we define it, the variable holds an unknown value until valid data is assigned. Constructor functions are special member functions that are called automatically when an object of that class is declared. The constructor function is used to initialize the data members of the object being defined. When designing a class, a complete set of constructor functions should be provided. Constructor functions have three unique properties:
* a constructor is called automatically when an object of that class is declared;
* the name of a constructor function is the name of the class;
* no return value is associated with a constructor function, and it is not a void function.
To illustrate, we define two constructor functions to initialize the class members. One function initializes x and y to zero; the other initializes x and y to values in the declaration statement. The two declarations are the first ones in the public declaration list in the following code:
// These statements define a class for xy-coordinates.
// Assume that this declaration is stored in xy_coordinate.h.
// The update is the addition of two constructor functions.
#include <iostream>
#include <cmath>
using namespace std;
class xy_coordinate
{
// Declare two constructor functions and six function
// prototypes for public members.
public:
xy_coordinate();
xy_coordinate(double a, double b);
void input();
void print();
double radius();
double angle();
// Declare private data members.
private:
double x, y;
};
The default constructor is called automatically whenever an object is defined in a declaration as follows:
xy_coordinate pt1;
Thus pt1 is an object of the class xy-coordinate. The data members of the object pt1 are initialized to the values assigned by the default constructor function xy-coordinate(). The constructor function with parameters is called automatically whenever an object is defined in a declaration statement as follows:
xy_coordinate pt2(3,4);
The data members of the object pt2 will be initialized to the values passed through the parameter list using the constructor function xy-coordinate(double a, double b). Thus, x is given the value 3 and y is given the value 4.
Constructor functions are programmer-defined functions. Here are the constructor functions that should be added to the class implementation file:
// This constructor function initializes x and y to zero.
xy_coordinate::xy_coordinate()
{
x = 0;
y = 0;
}
// This constructor function initializes x and y to parameters.
xy_coordinate::xy_coordinate(double a, double b)
{
x = a;
y = b;
}
Class Operators
The assignment operator is defined for objects of the same class type. If pt1 and pt2 are both xy_coordinate objects, then this statement is a valid statement:
pt1 = pt2;
Each data member of the object pt1 is assigned the value of the corresponding data member of the object pt2. However, the C++ arithmetic operators and relational operators cannot automatically be used with a programmer-defined class type. This comparison is not valid:
if (pt1 == pt2) (invalid comparison)
A class definition can include a set of operators to be used with objects of the class. The ability to overload operators is a powerful feature in C++. Overloading operators allows a programmer-defined data type to be used as easily as any predefined data type. As an example, consider the arithmetic operators defined in C++. These operators are defined to operate on all predefined data types. However, they are not defined for objects from programmer-defined data types. When designing a class data type, a set of arithmetic operators that work on objects of the class may be included. Operators are included in a class definition in the same way as member functions, except that the keyword operator is used. It is followed by the name of the function, where the name of the function is one of the predefined C++ operators. Only predefined operators may be overloaded. You may not, for example, define a new operator ** to perform exponentiation since this operator is not one of the predefined operators in C++. Next lecture, we illustrate the use of overloaded operators in the definition of a complex number class that includes the arithmetic operators (i.e., + , -, *, /).
Homework:
Define a class to represent a date. A date is defined using three integer variables: month, day, and year. Include member function definitions to
• input a date;
• print a date as month/day/year (10/1/1999);
• print a date as month day, year (October 1, 1999);
• initialize a date object.
Write a sample program that allows the user to enter the date using the date input function and prints the data in each of the defined forms using the class member functions.
Wednesday, December 12, 2018
Day 25 11/27/18
These problems relate to the program developed in this section for comparing hand measurements.
1. Modify the program so that it reads the unknown measurement from the keyboard.
2. Modify the program so that it reads the known measurement from a data file and contains a loop that
compares the unknown to all measurements in the file.
3. Modify the program in problem 2 so that it also prints the minimum distance measurement.
4. Modify the program in problem 3 so that it prints the entry number with the minimum distance, as in
“Known 4 has best match.”
5. Modify the program in problem 4 so that it prints all entries with the minimum distance.
#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;
#define FILENAME "known.txt"
int main(void)
{
ifstream known;
known.open(FILENAME);
if (known.fail()){
cout << "Error opening input file." << endl;
}
//Declare and initialize variables.
int k=0;
double minimum1=100;
double minimum2=100;
double unknown[5], known1[5];
double distance(double hand_1[5],double hand_2[5]);
cout << "Enter the 5 unknown values:" << endl;
for(int b=0;b<5;b++){
cin >> unknown[b];
}
while(!known.eof()){
known >> known1[k];
k++;
}
for(int c=0;c<5;c++){
if(unknown[c]<minimum1){
minimum1 = unknown[c];
}
}
for(int d=0;d<5;d++){
if(known1[d]<minimum2){
minimum2 = known1[d];
}
}
if(minimum1<minimum2){
minimum2 = minimum1;
}
// Compute and print distance.
cout << "Distance: " << distance(unknown,known1) << endl;
cout << "minimum:" << minimum2 << endl;
known.close();
// Exit program.
return 0;
}
//-----------------------------------------------------------------
// This function computes the distance between two hand measurements.
double distance(double hand_1[5],double hand_2[5])
{
// Declare variables.
int a;
double sum=0;
// Compute sum of absolute value differences.
for (a=0; a<=4; a++)
sum = sum + fabs(hand_1[a]-hand_2[a]);
// Return distance value.
return sum;
}
#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;
#define FILENAME "known.txt"
int main(void)
{
ifstream known;
known.open(FILENAME);
if (known.fail()){
cout << "Error opening input file." << endl;
}
//Declare and initialize variables.
int k=0;
double minimum1=100;
double minimum2=100;
double unknown[5], known1[5];
double distance(double hand_1[5],double hand_2[5]);
cout << "Enter the 5 unknown values:" << endl;
for(int b=0;b<5;b++){
cin >> unknown[b];
}
while(!known.eof()){
known >> known1[k];
k++;
}
for(int c=0;c<5;c++){
if(unknown[c]<minimum1){
minimum1 = unknown[c];
}
}
for(int d=0;d<5;d++){
if(known1[d]<minimum2){
minimum2 = known1[d];
}
}
if(minimum1<minimum2){
minimum2 = minimum1;
}
// Compute and print distance.
cout << "Distance: " << distance(unknown,known1) << endl;
cout << "minimum:" << minimum2 << endl;
known.close();
// Exit program.
return 0;
}
//-----------------------------------------------------------------
// This function computes the distance between two hand measurements.
double distance(double hand_1[5],double hand_2[5])
{
// Declare variables.
int a;
double sum=0;
// Compute sum of absolute value differences.
for (a=0; a<=4; a++)
sum = sum + fabs(hand_1[a]-hand_2[a]);
// Return distance value.
return sum;
}
Day 22 11/8/18
These problems relate to the program developed in this section to analyze tsunami data.
1. Modify the program to find and print the number of tsunamis in the file during the same
year as the maximum wave height.
2. Modify the program to find and print the date of the tsunami with the largest number of
fatalities.
3. Modify the program to find and print the locations for all tsunamis with over
100 fatalities.
4. Modify the program so that it counts the number of tsunamis that occurred during the
month of July.
5. Modify the program so that it prints the number of tsunamis in Peru. Assume that the
location might also include the city in Peru, so you will need to search the character
string for the substring "Peru".
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define FILENAME "waves2.txt"
// Define structure to represent a tsunami.
struct tsunami
{
int mo, da, yr, fatalities;
double max_height;
char location[20];
};
int main(void)
{
// Declare variables.
int k=0, npts;
double max=0, sum=0, ave, maxheight[10];
char location1[10];
struct tsunami tk[100];
FILE *waves;
// Read and print information from the file. /
waves = fopen(FILENAME,"r");
if (waves == NULL)
printf("Error opening data file. \n");
else
{
for(int a=0;a<10;a++){
fscanf(waves,"%d %d %d %s %lf %d",&tk[a].mo,&tk[a].da,&tk[a].yr,&tk[a].location,&tk[a].max_height,&tk[a].fatalities);
sum += tk[a].max_height;
if (tk[a].max_height > max){
max = tk[a].max_height;
}
maxheight[a]=tk[a].max_height*3.28;
k++;
npts = k;
}
ave = sum/npts;
printf("Summary Information for Tsunamis \n");
printf("Maximum Wave Height (in feet): %.2f \n",max*3.28);
printf("Average Wave Height (in feet): %.2f \n",ave*3.28);
printf("Tsunamis with greater than average heights: \n");
for (k=0; k<npts; k++){
if(maxheight[k]>ave*3.28){
printf("%s \n",tk[k].location);
}}
fclose(waves);
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define FILENAME "waves2.txt"
// Define structure to represent a tsunami.
struct tsunami
{
int mo, da, yr, fatalities;
double max_height;
char location[20];
};
int main(void)
{
// Declare variables.
int k=0, npts;
double max=0, sum=0, ave, maxheight[10];
char location1[10];
struct tsunami tk[100];
FILE *waves;
// Read and print information from the file. /
waves = fopen(FILENAME,"r");
if (waves == NULL)
printf("Error opening data file. \n");
else
{
for(int a=0;a<10;a++){
fscanf(waves,"%d %d %d %s %lf %d",&tk[a].mo,&tk[a].da,&tk[a].yr,&tk[a].location,&tk[a].max_height,&tk[a].fatalities);
sum += tk[a].max_height;
if (tk[a].max_height > max){
max = tk[a].max_height;
}
maxheight[a]=tk[a].max_height*3.28;
k++;
npts = k;
}
ave = sum/npts;
printf("Summary Information for Tsunamis \n");
printf("Maximum Wave Height (in feet): %.2f \n",max*3.28);
printf("Average Wave Height (in feet): %.2f \n",ave*3.28);
printf("Tsunamis with greater than average heights: \n");
for (k=0; k<npts; k++){
if(maxheight[k]>ave*3.28){
printf("%s \n",tk[k].location);
}}
fclose(waves);
}
return 0;
}
Day 21 11/6/18
Modify
1. Modify the program so that it prints the long string and the short string.
2. Modify the program so that it allows the user to enter the long string and the short string.
3. Modify the program so that the long string is read from a data file and the short string is input from
the user.
4. Modify the program so that it will work with either lowercase or uppercase characters.
5. Modify the program so that it checks to be sure that the length of the short string is less than the
length of the long string.
/* This program initializes a long character string and a short */
/* character string. It then prints the locations of the short */
/* string in the long string. It also prints the number of */
/* occurrences of the short string in the long string. */
#include <stdio.h>
#include <string.h>
#define FILENAME "DNA1.txt"
#define MAX_SIZE 1000
int main(void)
{
/* Declare and initialize variables. */
FILE *dna;
dna = fopen(FILENAME,"r");
if (dna == NULL){
printf("Error opening input file. \n");
}
else{
int count=0;
int size1;
int size2;
int val = 0;
char long_str[MAX_SIZE], short_str[MAX_SIZE];
while(val==0){
printf("how long is the long string?\n");
scanf("%i", &size1);
printf("how long is the short string?\n");
scanf("%i", &size2);
if(size2>size1){
printf("Error short string cannot be larger than long string, please reenter all credentials\n");
}
if(size1>=size2){
val++;
}
}
for(int a = 0;a<size1;a++){
fscanf(dna,"%c",&long_str[a]);
}
printf("enter the short string\n");
for(int b = 0;b<size2;b++){
scanf("%s", &short_str[b]);
if(short_str[b]==97){
short_str[b]=65;
}
if(short_str[b]==99){
short_str[b]=67;
}
if(short_str[b]==116){
short_str[b]=84;
}
if(short_str[b]==103){
short_str[b]=71;
}
}
char *ptr1=long_str, *ptr2=short_str;
/* Count the number of occurrences of short_str in long_str. */
/* While the function strstr does not return NULL, increment */
/* count and move ptr1 to next character of the long string. */
while ((ptr1=strstr(ptr1,ptr2)) != NULL)
{
printf("location %i \n",ptr1-long_str+1);
count++;
ptr1++;
}
/* Print number of occurrences. */
printf("number of occurrences: %i \n",count);
printf("Long string: ");
for(int c = 0;c<size1;c++){
printf("%c", long_str[c]);
}
printf("\nShort string: ");
for(int d = 0;d<size2;d++){
printf("%c", short_str[d]);
}
}
/* Exit program. */
fclose(dna);
return 0;
}
These problems relate to the program developed in this section. 1. Modify the program so that it also counts and prints the number of whorls for the hand. 2. Modify the program so that it also counts and prints the number of arches for the hand. 3. Modify the program so that it also counts and prints the number of loops for the hand. 4. Modify the program so that it combines problems 1, 2, and 3 and thus prints the numbers of the three different categories for the fingertips. 5. Modify the program in problem 4 so that it prints the percentages of the three different categories for the fingertips.
/* This program stores fingerprint information in a structure. */
/* It then references a function to compute the overall category.*/
#include <stdio.h>
#include <math.h>
/* Define a structure for the fingerprint information. */
/* The order for fingertips is right hand, thumb to pinky, */
/* and left hand, thumb to pinky. The codes are L for loops, */
/* W for whorls, and A for arches. */
struct fingerprint
{
int ID_number;
double overall_category;
char fingertip[10];
};
int main(void)
{
/* Declare and initialize variables. */
struct fingerprint new_print;
double compute_category(struct fingerprint f);
void count(struct fingerprint f);
/* Specify information for the new fingerprint. */
new_print.ID_number = 2491009;
new_print.overall_category = 0;
new_print.fingertip[0] = 'W';
new_print.fingertip[1] = 'L';
new_print.fingertip[2] = 'L';
new_print.fingertip[3] = 'W';
new_print.fingertip[4] = 'A';
new_print.fingertip[5] = 'L';
new_print.fingertip[6] = 'L';
new_print.fingertip[7] = 'W';
new_print.fingertip[8] = 'A';
new_print.fingertip[9] = 'L';
/* Reference function to compute overall category. */
new_print.overall_category = compute_category(new_print);
/* Print overall category computed by the function. */
printf("Fingerprint Analysis for ID: %i \n",new_print.ID_number);
printf("Overall Category: %.2f \n",new_print.overall_category);
count(new_print);
/* Exit program. */
return 0;
}
/*--------------------------------------------------------------*/
/* This function computes the overall category */
/* for a fingerprint. */
double compute_category(struct fingerprint f)
{
/* Declare and initialize variables. */
double Rt=0, Ri=0, Rm=0, Rr=0, Rp=0, Lt=0, Li=0, Lm=0, Lr=0,
Lp=0, num, den;
/* Set values based on whorls. */
if (f.fingertip[0] == 'W')
Rt = 16;
if (f.fingertip[1] == 'W')
Ri = 16;
if (f.fingertip[2] == 'W')
Rm = 8;
if (f.fingertip[3] == 'W')
Rr = 8;
if (f.fingertip[4] == 'W')
Rp = 4;
if (f.fingertip[5] == 'W')
Lt = 4;
if (f.fingertip[6] == 'W')
Li = 2;
if (f.fingertip[7] == 'W')
Lm = 2;
/* Compute the numerator and denominator for overall category. */
num = Ri + Rr + Lt + Lm + Lp + 1;
den = Rt + Rm + Rp + Li + Lr + 1;
return num/den;
}
void count(struct fingerprint f){
int countw=0, countl=0, counta=0;
float percentl, percenta, percentw;
if (f.fingertip[0] == 'W'){
countw++;
}
if (f.fingertip[1] == 'W'){
countw++;
}
if (f.fingertip[2] == 'W'){
countw++;
}
if (f.fingertip[3] == 'W'){
countw++;
}
if (f.fingertip[4] == 'W'){
countw++;
}
if (f.fingertip[5] == 'W'){
countw++;
}
if (f.fingertip[6] == 'W'){
countw++;
}
if (f.fingertip[7] == 'W'){
countw++;
}
if (f.fingertip[8] == 'W'){
countw++;
}
if (f.fingertip[9] == 'W'){
countw++;
}
percentw=((countw*100)/10);
printf("the number of whorls is %i \nthe percentage of the fingertips being whorls is %f%%\n", countw, percentw);
if (f.fingertip[0] == 'L'){
countl++;
}
if (f.fingertip[1] == 'L'){
countl++;
}
if (f.fingertip[2] == 'L'){
countl++;
}
if (f.fingertip[3] == 'L'){
countl++;
}
if (f.fingertip[4] == 'L'){
countl++;
}
if (f.fingertip[5] == 'L'){
countl++;
}
if (f.fingertip[6] == 'L'){
countl++;
}
if (f.fingertip[7] == 'L'){
countl++;
}
if (f.fingertip[8] == 'L'){
countl++;
}
if (f.fingertip[9] == 'L'){
countl++;
}
percentl=((countl*100)/10);
printf("the number of loops is %i \nthe percentage of the fingertips being loops is %f%%\n", countl, percentl);
if (f.fingertip[0] == 'A'){
counta++;
}
if (f.fingertip[1] == 'A'){
counta++;
}
if (f.fingertip[2] == 'A'){
counta++;
}
if (f.fingertip[3] == 'A'){
counta++;
}
if (f.fingertip[4] == 'A'){
counta++;
}
if (f.fingertip[5] == 'A'){
counta++;
}
if (f.fingertip[6] == 'A'){
counta++;
}
if (f.fingertip[7] == 'A'){
counta++;
}
if (f.fingertip[8] == 'A'){
counta++;
}
if (f.fingertip[9] == 'A'){
counta++;
}
percenta=((counta*100)/10);
printf("the number of arches is %i \nthe percentage of the fingertips being arches is %f%%\n", counta, percenta);
return;
}
/* This program initializes a long character string and a short */
/* character string. It then prints the locations of the short */
/* string in the long string. It also prints the number of */
/* occurrences of the short string in the long string. */
#include <stdio.h>
#include <string.h>
#define FILENAME "DNA1.txt"
#define MAX_SIZE 1000
int main(void)
{
/* Declare and initialize variables. */
FILE *dna;
dna = fopen(FILENAME,"r");
if (dna == NULL){
printf("Error opening input file. \n");
}
else{
int count=0;
int size1;
int size2;
int val = 0;
char long_str[MAX_SIZE], short_str[MAX_SIZE];
while(val==0){
printf("how long is the long string?\n");
scanf("%i", &size1);
printf("how long is the short string?\n");
scanf("%i", &size2);
if(size2>size1){
printf("Error short string cannot be larger than long string, please reenter all credentials\n");
}
if(size1>=size2){
val++;
}
}
for(int a = 0;a<size1;a++){
fscanf(dna,"%c",&long_str[a]);
}
printf("enter the short string\n");
for(int b = 0;b<size2;b++){
scanf("%s", &short_str[b]);
if(short_str[b]==97){
short_str[b]=65;
}
if(short_str[b]==99){
short_str[b]=67;
}
if(short_str[b]==116){
short_str[b]=84;
}
if(short_str[b]==103){
short_str[b]=71;
}
}
char *ptr1=long_str, *ptr2=short_str;
/* Count the number of occurrences of short_str in long_str. */
/* While the function strstr does not return NULL, increment */
/* count and move ptr1 to next character of the long string. */
while ((ptr1=strstr(ptr1,ptr2)) != NULL)
{
printf("location %i \n",ptr1-long_str+1);
count++;
ptr1++;
}
/* Print number of occurrences. */
printf("number of occurrences: %i \n",count);
printf("Long string: ");
for(int c = 0;c<size1;c++){
printf("%c", long_str[c]);
}
printf("\nShort string: ");
for(int d = 0;d<size2;d++){
printf("%c", short_str[d]);
}
}
/* Exit program. */
fclose(dna);
return 0;
}
These problems relate to the program developed in this section. 1. Modify the program so that it also counts and prints the number of whorls for the hand. 2. Modify the program so that it also counts and prints the number of arches for the hand. 3. Modify the program so that it also counts and prints the number of loops for the hand. 4. Modify the program so that it combines problems 1, 2, and 3 and thus prints the numbers of the three different categories for the fingertips. 5. Modify the program in problem 4 so that it prints the percentages of the three different categories for the fingertips.
/* This program stores fingerprint information in a structure. */
/* It then references a function to compute the overall category.*/
#include <stdio.h>
#include <math.h>
/* Define a structure for the fingerprint information. */
/* The order for fingertips is right hand, thumb to pinky, */
/* and left hand, thumb to pinky. The codes are L for loops, */
/* W for whorls, and A for arches. */
struct fingerprint
{
int ID_number;
double overall_category;
char fingertip[10];
};
int main(void)
{
/* Declare and initialize variables. */
struct fingerprint new_print;
double compute_category(struct fingerprint f);
void count(struct fingerprint f);
/* Specify information for the new fingerprint. */
new_print.ID_number = 2491009;
new_print.overall_category = 0;
new_print.fingertip[0] = 'W';
new_print.fingertip[1] = 'L';
new_print.fingertip[2] = 'L';
new_print.fingertip[3] = 'W';
new_print.fingertip[4] = 'A';
new_print.fingertip[5] = 'L';
new_print.fingertip[6] = 'L';
new_print.fingertip[7] = 'W';
new_print.fingertip[8] = 'A';
new_print.fingertip[9] = 'L';
/* Reference function to compute overall category. */
new_print.overall_category = compute_category(new_print);
/* Print overall category computed by the function. */
printf("Fingerprint Analysis for ID: %i \n",new_print.ID_number);
printf("Overall Category: %.2f \n",new_print.overall_category);
count(new_print);
/* Exit program. */
return 0;
}
/*--------------------------------------------------------------*/
/* This function computes the overall category */
/* for a fingerprint. */
double compute_category(struct fingerprint f)
{
/* Declare and initialize variables. */
double Rt=0, Ri=0, Rm=0, Rr=0, Rp=0, Lt=0, Li=0, Lm=0, Lr=0,
Lp=0, num, den;
/* Set values based on whorls. */
if (f.fingertip[0] == 'W')
Rt = 16;
if (f.fingertip[1] == 'W')
Ri = 16;
if (f.fingertip[2] == 'W')
Rm = 8;
if (f.fingertip[3] == 'W')
Rr = 8;
if (f.fingertip[4] == 'W')
Rp = 4;
if (f.fingertip[5] == 'W')
Lt = 4;
if (f.fingertip[6] == 'W')
Li = 2;
if (f.fingertip[7] == 'W')
Lm = 2;
/* Compute the numerator and denominator for overall category. */
num = Ri + Rr + Lt + Lm + Lp + 1;
den = Rt + Rm + Rp + Li + Lr + 1;
return num/den;
}
void count(struct fingerprint f){
int countw=0, countl=0, counta=0;
float percentl, percenta, percentw;
if (f.fingertip[0] == 'W'){
countw++;
}
if (f.fingertip[1] == 'W'){
countw++;
}
if (f.fingertip[2] == 'W'){
countw++;
}
if (f.fingertip[3] == 'W'){
countw++;
}
if (f.fingertip[4] == 'W'){
countw++;
}
if (f.fingertip[5] == 'W'){
countw++;
}
if (f.fingertip[6] == 'W'){
countw++;
}
if (f.fingertip[7] == 'W'){
countw++;
}
if (f.fingertip[8] == 'W'){
countw++;
}
if (f.fingertip[9] == 'W'){
countw++;
}
percentw=((countw*100)/10);
printf("the number of whorls is %i \nthe percentage of the fingertips being whorls is %f%%\n", countw, percentw);
if (f.fingertip[0] == 'L'){
countl++;
}
if (f.fingertip[1] == 'L'){
countl++;
}
if (f.fingertip[2] == 'L'){
countl++;
}
if (f.fingertip[3] == 'L'){
countl++;
}
if (f.fingertip[4] == 'L'){
countl++;
}
if (f.fingertip[5] == 'L'){
countl++;
}
if (f.fingertip[6] == 'L'){
countl++;
}
if (f.fingertip[7] == 'L'){
countl++;
}
if (f.fingertip[8] == 'L'){
countl++;
}
if (f.fingertip[9] == 'L'){
countl++;
}
percentl=((countl*100)/10);
printf("the number of loops is %i \nthe percentage of the fingertips being loops is %f%%\n", countl, percentl);
if (f.fingertip[0] == 'A'){
counta++;
}
if (f.fingertip[1] == 'A'){
counta++;
}
if (f.fingertip[2] == 'A'){
counta++;
}
if (f.fingertip[3] == 'A'){
counta++;
}
if (f.fingertip[4] == 'A'){
counta++;
}
if (f.fingertip[5] == 'A'){
counta++;
}
if (f.fingertip[6] == 'A'){
counta++;
}
if (f.fingertip[7] == 'A'){
counta++;
}
if (f.fingertip[8] == 'A'){
counta++;
}
if (f.fingertip[9] == 'A'){
counta++;
}
percenta=((counta*100)/10);
printf("the number of arches is %i \nthe percentage of the fingertips being arches is %f%%\n", counta, percenta);
return;
}
Day 19/20 10/30/18-11/1/18
Modify your seismic program so that it can work with arbitrarily large data files without the use of a
header line! A data file will be posted on edmodo for your to process.
/* This program reads a seismic data file and then */
/* determines the times of possible seismic events. */
#include <stdio.h>
#define FILENAME "seismic1.txt"
#define MAX_SIZE 1000
double THRESHOLD;
int main(void)
{
int val=0;
while(val==0){
printf("Enter the Threshold Number:\n");
scanf("%lf", &THRESHOLD);
if(THRESHOLD<1){
printf("Please Enter a Positive Value above 1\n");
}
else{
val++;
}}
/* Declare variables and function prototypes. */
int k, npts, short_window, long_window, count=0;
double sensor[MAX_SIZE], time[2], time_incr, short_power, long_power, ratio;
FILE *file_ptr;
double power_w(double *ptr,int n);
/* Read sensor data file. */
file_ptr = fopen(FILENAME,"r");
if (file_ptr == NULL)
printf("Error opening input file. \n");
else
{
fscanf(file_ptr,"%d %lf",&npts,&time_incr);
if (npts > MAX_SIZE)
printf("Data file too large for array. \n");
else
{
/* Read data into an array. */
for (k=0; k<=npts-1; k++)
fscanf(file_ptr,"%lf",&sensor[k]);
/* Read window sizes from the keyboard. */
printf("Enter number of points for short window: \n");
scanf("%d",&short_window);
printf("Enter number of points for long window: \n");
scanf("%d",&long_window);
/* Compute power ratios and search for events. */
for (k=long_window-1; k<=npts-1; k++)
{
short_power = power_w(&sensor[k],short_window);
long_power = power_w(&sensor[k],long_window);
ratio = short_power/long_power;
if (ratio > THRESHOLD){
printf("Possible event at %f seconds \n",time_incr*k);
count++;
time[k]=time_incr*k;}
}
for(int j=long_window-1; j<=npts-1; j++){
if((time[j]-time[j+1])==.01){
count++;
}}
printf("%d Events Occured", count);
/* Close file. */
fclose(file_ptr);
}
}
return 0;
}
/*????????????????????????????????????????????????????????????-*/
/* This function computes the average power in a specified */
/* window of a double array. */
double power_w(double *ptr, int n)
{
/* Declare and initialize variables. */
int k;
double xsquare=0;
/* Compute sum of values squared in the array x. */
for (k=0; k<=n-1; k++)
xsquare += *(ptr-k)*(*(ptr-k));
/* Return the average squared value. */
return xsquare/n;
}
/* This program reads a seismic data file and then */
/* determines the times of possible seismic events. */
#include <stdio.h>
#define FILENAME "seismic1.txt"
#define MAX_SIZE 1000
double THRESHOLD;
int main(void)
{
int val=0;
while(val==0){
printf("Enter the Threshold Number:\n");
scanf("%lf", &THRESHOLD);
if(THRESHOLD<1){
printf("Please Enter a Positive Value above 1\n");
}
else{
val++;
}}
/* Declare variables and function prototypes. */
int k, npts, short_window, long_window, count=0;
double sensor[MAX_SIZE], time[2], time_incr, short_power, long_power, ratio;
FILE *file_ptr;
double power_w(double *ptr,int n);
/* Read sensor data file. */
file_ptr = fopen(FILENAME,"r");
if (file_ptr == NULL)
printf("Error opening input file. \n");
else
{
fscanf(file_ptr,"%d %lf",&npts,&time_incr);
if (npts > MAX_SIZE)
printf("Data file too large for array. \n");
else
{
/* Read data into an array. */
for (k=0; k<=npts-1; k++)
fscanf(file_ptr,"%lf",&sensor[k]);
/* Read window sizes from the keyboard. */
printf("Enter number of points for short window: \n");
scanf("%d",&short_window);
printf("Enter number of points for long window: \n");
scanf("%d",&long_window);
/* Compute power ratios and search for events. */
for (k=long_window-1; k<=npts-1; k++)
{
short_power = power_w(&sensor[k],short_window);
long_power = power_w(&sensor[k],long_window);
ratio = short_power/long_power;
if (ratio > THRESHOLD){
printf("Possible event at %f seconds \n",time_incr*k);
count++;
time[k]=time_incr*k;}
}
for(int j=long_window-1; j<=npts-1; j++){
if((time[j]-time[j+1])==.01){
count++;
}}
printf("%d Events Occured", count);
/* Close file. */
fclose(file_ptr);
}
}
return 0;
}
/*????????????????????????????????????????????????????????????-*/
/* This function computes the average power in a specified */
/* window of a double array. */
double power_w(double *ptr, int n)
{
/* Declare and initialize variables. */
int k;
double xsquare=0;
/* Compute sum of values squared in the array x. */
for (k=0; k<=n-1; k++)
xsquare += *(ptr-k)*(*(ptr-k));
/* Return the average squared value. */
return xsquare/n;
}
Thursday, October 25, 2018
Day 17 10/23/18
Arduino Homework
Extend you program to act under serial control.
int M1_Left = 11; //Motor Input 1
int M1_Right = 10; //Motor Input 2
int POT = A1;
int val = 0;
int value = 0;
char value2 = 0;
int value3 = 0;
int velocity = 75;
void setup()
{
Serial.begin(9600);
Serial.println("Begin Motor Control Sequence");
Serial.println("Enter Number for Control Option:");
Serial.println("1 for Forward");
Serial.println("2 for Reverse");
Serial.println("3 for stop");
Serial.println("+ for speed increase");
Serial.println("- for speed decrease");
pinMode(M1_Left, OUTPUT);
pinMode(M1_Right , OUTPUT);
}
void loop(){
while(Serial.available() > 0){
value2 = Serial.read();
Serial.println(value2);
if(value2 == '1'){
value=0;
while(value == 0){
forward(velocity);
value2 = Serial.read();
Serial.println(value2);
if(value2 == '+'){
velocity+=10;
}
if(value2 == '-'){
velocity-=10;
}
if(value2 == '2'){
value++;
}
if(value2 == '3'){
value++;
}
}
}
if(value2 == '2'){
value=0;
while(value == 0){
reverse(velocity);
value2 = Serial.read();
Serial.println(value2);
if(value2 == '+'){
velocity+=10;
}
if(value2 == '-'){
velocity-=10;
}
if(value2 == '1'){
value++;
}
if(value2 == '3'){
value++;
}
}
}
if(value2 == '3'){
brake();
}
}
/* val = analogRead(POT);
if(val > 562){
velocity = map(val, 563, 1023, 0, 255);
forward(velocity);
Serial.println(velocity);
}
if(val < 462){
velocity = map(val, 461, 0, 0, 255);
reverse(velocity);
Serial.println(velocity);
}
else{
brake();
}*/
}
void forward(int direction)
{
analogWrite(M1_Right, 0);
analogWrite(M1_Left, direction);
}
void reverse(int direction)
{
analogWrite(M1_Left, 0);
analogWrite(M1_Right, direction);
}
void brake(){
analogWrite(M1_Left, 0);
analogWrite(M1_Right , 0);
}
ENSO and Seismic Homework
1. Modify the program to find and print the maximum La Niña conditions.
2. Modify the program to find the conditions closest to zero. These would be the conditions that are closest to normal.
3. Modify the program so that it prints all years and quarters with El Niño conditions.
/* This program reads a data file of ENSO index values and */
/* determines the maximum El Nino condition in the file. */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define FILENAME "ENSO1.txt"
#define MAX_SIZE 1000
int main(void)
{
/* Declare variables and function prototypes. */
int k=0,l=0, year[MAX_SIZE], year2[MAX_SIZE], qtr[MAX_SIZE], qtr2[MAX_SIZE], max_k=0, min_k=0, find0=0, count=0;
double index[MAX_SIZE], data[MAX_SIZE];
FILE *enso;
/* Read sensor data file. */
enso = fopen(FILENAME,"r");
if (enso == NULL)
printf("Error opening input file. \n");
else
{
while (fscanf(enso,"%d %d %lf", year+k,qtr+k,index+k)==3){
if (*(index+k) > *(index+max_k)){
max_k = k;}
if (*(index+k) < *(index+min_k)){
min_k = k;}
if(*(index+k) > 0){
data[l] = index[k];
year2[l] = *(year+k);
qtr2[l] = *(qtr+k);
l++;
count++;
}
if (fabs(*(index+k)) >= 0){
if (fabs(*(index+k)) < fabs(*(index+find0))){
find0 = k;}}
k++;
}
/* Print data for maximum El Nino condition. */
printf("Maximum El Nino Conditions in Data File \n");
printf("Year: %d, Quarter: %d \n", *(year+max_k),*(qtr+max_k));
printf("Maximum la Nina Conditions in Data File \n");
printf("Year: %d, Quarter: %d \n", *(year+min_k),*(qtr+min_k));
printf("Conditions closest to 0 in Data File \n");
printf("Year: %d, Quarter: %d \n\n", *(year+find0),*(qtr+find0));
for(l=0;l<count;l++){
printf("YEAR: %d ", year2[l]);
printf("QUARTER: %d ", qtr2[l]);
printf("DATA: %5.1f\n", data[l]);}
/* Close file. */
fclose(enso);
}
/* Exit program. */
return 0;
}
1. Allow the user to enter the threshold value. Check the value to be sure that it is a positive value greater than 1.
2. Print the number of events detected by the program. (Assume that events with contiguous times are all part of the same event. Thus, for the hand example, one event was detected.
/* This program reads a seismic data file and then */
/* determines the times of possible seismic events. */
#include <stdio.h>
#define FILENAME "seismic1.txt"
#define MAX_SIZE 1000
double THRESHOLD;
int main(void)
{
int val=0;
while(val==0){
printf("Enter the Threshold Number:\n");
scanf("%lf", &THRESHOLD);
if(THRESHOLD<1){
printf("Please Enter a Positive Value above 1\n");
}
else{
val++;
}}
/* Declare variables and function prototypes. */
int k, npts, short_window, long_window, count=0;
double sensor[MAX_SIZE], time[2], time_incr, short_power, long_power, ratio;
FILE *file_ptr;
double power_w(double *ptr,int n);
/* Read sensor data file. */
file_ptr = fopen(FILENAME,"r");
if (file_ptr == NULL)
printf("Error opening input file. \n");
else
{
fscanf(file_ptr,"%d %lf",&npts,&time_incr);
if (npts > MAX_SIZE)
printf("Data file too large for array. \n");
else
{
/* Read data into an array. */
for (k=0; k<=npts-1; k++)
fscanf(file_ptr,"%lf",&sensor[k]);
/* Read window sizes from the keyboard. */
printf("Enter number of points for short window: \n");
scanf("%d",&short_window);
printf("Enter number of points for long window: \n");
scanf("%d",&long_window);
/* Compute power ratios and search for events. */
for (k=long_window-1; k<=npts-1; k++)
{
short_power = power_w(&sensor[k],short_window);
long_power = power_w(&sensor[k],long_window);
ratio = short_power/long_power;
if (ratio > THRESHOLD){
printf("Possible event at %f seconds \n",time_incr*k);
count++;
time[k]=time_incr*k;}
}
for(int j=long_window-1; j<=npts-1; j++){
if((time[j]-time[j+1])==.01){
count++;
}}
printf("%d Events Occured", count);
/* Close file. */
fclose(file_ptr);
}
}
return 0;
}
/*????????????????????????????????????????????????????????????-*/
/* This function computes the average power in a specified */
/* window of a double array. */
double power_w(double *ptr, int n)
{
/* Declare and initialize variables. */
int k;
double xsquare=0;
/* Compute sum of values squared in the array x. */
for (k=0; k<=n-1; k++)
xsquare += *(ptr-k)*(*(ptr-k));
/* Return the average squared value. */
return xsquare/n;
}
Extend you program to act under serial control.
int M1_Left = 11; //Motor Input 1
int M1_Right = 10; //Motor Input 2
int POT = A1;
int val = 0;
int value = 0;
char value2 = 0;
int value3 = 0;
int velocity = 75;
void setup()
{
Serial.begin(9600);
Serial.println("Begin Motor Control Sequence");
Serial.println("Enter Number for Control Option:");
Serial.println("1 for Forward");
Serial.println("2 for Reverse");
Serial.println("3 for stop");
Serial.println("+ for speed increase");
Serial.println("- for speed decrease");
pinMode(M1_Left, OUTPUT);
pinMode(M1_Right , OUTPUT);
}
void loop(){
while(Serial.available() > 0){
value2 = Serial.read();
Serial.println(value2);
if(value2 == '1'){
value=0;
while(value == 0){
forward(velocity);
value2 = Serial.read();
Serial.println(value2);
if(value2 == '+'){
velocity+=10;
}
if(value2 == '-'){
velocity-=10;
}
if(value2 == '2'){
value++;
}
if(value2 == '3'){
value++;
}
}
}
if(value2 == '2'){
value=0;
while(value == 0){
reverse(velocity);
value2 = Serial.read();
Serial.println(value2);
if(value2 == '+'){
velocity+=10;
}
if(value2 == '-'){
velocity-=10;
}
if(value2 == '1'){
value++;
}
if(value2 == '3'){
value++;
}
}
}
if(value2 == '3'){
brake();
}
}
/* val = analogRead(POT);
if(val > 562){
velocity = map(val, 563, 1023, 0, 255);
forward(velocity);
Serial.println(velocity);
}
if(val < 462){
velocity = map(val, 461, 0, 0, 255);
reverse(velocity);
Serial.println(velocity);
}
else{
brake();
}*/
}
void forward(int direction)
{
analogWrite(M1_Right, 0);
analogWrite(M1_Left, direction);
}
void reverse(int direction)
{
analogWrite(M1_Left, 0);
analogWrite(M1_Right, direction);
}
void brake(){
analogWrite(M1_Left, 0);
analogWrite(M1_Right , 0);
}
ENSO and Seismic Homework
1. Modify the program to find and print the maximum La Niña conditions.
2. Modify the program to find the conditions closest to zero. These would be the conditions that are closest to normal.
3. Modify the program so that it prints all years and quarters with El Niño conditions.
/* This program reads a data file of ENSO index values and */
/* determines the maximum El Nino condition in the file. */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define FILENAME "ENSO1.txt"
#define MAX_SIZE 1000
int main(void)
{
/* Declare variables and function prototypes. */
int k=0,l=0, year[MAX_SIZE], year2[MAX_SIZE], qtr[MAX_SIZE], qtr2[MAX_SIZE], max_k=0, min_k=0, find0=0, count=0;
double index[MAX_SIZE], data[MAX_SIZE];
FILE *enso;
/* Read sensor data file. */
enso = fopen(FILENAME,"r");
if (enso == NULL)
printf("Error opening input file. \n");
else
{
while (fscanf(enso,"%d %d %lf", year+k,qtr+k,index+k)==3){
if (*(index+k) > *(index+max_k)){
max_k = k;}
if (*(index+k) < *(index+min_k)){
min_k = k;}
if(*(index+k) > 0){
data[l] = index[k];
year2[l] = *(year+k);
qtr2[l] = *(qtr+k);
l++;
count++;
}
if (fabs(*(index+k)) >= 0){
if (fabs(*(index+k)) < fabs(*(index+find0))){
find0 = k;}}
k++;
}
/* Print data for maximum El Nino condition. */
printf("Maximum El Nino Conditions in Data File \n");
printf("Year: %d, Quarter: %d \n", *(year+max_k),*(qtr+max_k));
printf("Maximum la Nina Conditions in Data File \n");
printf("Year: %d, Quarter: %d \n", *(year+min_k),*(qtr+min_k));
printf("Conditions closest to 0 in Data File \n");
printf("Year: %d, Quarter: %d \n\n", *(year+find0),*(qtr+find0));
for(l=0;l<count;l++){
printf("YEAR: %d ", year2[l]);
printf("QUARTER: %d ", qtr2[l]);
printf("DATA: %5.1f\n", data[l]);}
/* Close file. */
fclose(enso);
}
/* Exit program. */
return 0;
}
1. Allow the user to enter the threshold value. Check the value to be sure that it is a positive value greater than 1.
2. Print the number of events detected by the program. (Assume that events with contiguous times are all part of the same event. Thus, for the hand example, one event was detected.
/* This program reads a seismic data file and then */
/* determines the times of possible seismic events. */
#include <stdio.h>
#define FILENAME "seismic1.txt"
#define MAX_SIZE 1000
double THRESHOLD;
int main(void)
{
int val=0;
while(val==0){
printf("Enter the Threshold Number:\n");
scanf("%lf", &THRESHOLD);
if(THRESHOLD<1){
printf("Please Enter a Positive Value above 1\n");
}
else{
val++;
}}
/* Declare variables and function prototypes. */
int k, npts, short_window, long_window, count=0;
double sensor[MAX_SIZE], time[2], time_incr, short_power, long_power, ratio;
FILE *file_ptr;
double power_w(double *ptr,int n);
/* Read sensor data file. */
file_ptr = fopen(FILENAME,"r");
if (file_ptr == NULL)
printf("Error opening input file. \n");
else
{
fscanf(file_ptr,"%d %lf",&npts,&time_incr);
if (npts > MAX_SIZE)
printf("Data file too large for array. \n");
else
{
/* Read data into an array. */
for (k=0; k<=npts-1; k++)
fscanf(file_ptr,"%lf",&sensor[k]);
/* Read window sizes from the keyboard. */
printf("Enter number of points for short window: \n");
scanf("%d",&short_window);
printf("Enter number of points for long window: \n");
scanf("%d",&long_window);
/* Compute power ratios and search for events. */
for (k=long_window-1; k<=npts-1; k++)
{
short_power = power_w(&sensor[k],short_window);
long_power = power_w(&sensor[k],long_window);
ratio = short_power/long_power;
if (ratio > THRESHOLD){
printf("Possible event at %f seconds \n",time_incr*k);
count++;
time[k]=time_incr*k;}
}
for(int j=long_window-1; j<=npts-1; j++){
if((time[j]-time[j+1])==.01){
count++;
}}
printf("%d Events Occured", count);
/* Close file. */
fclose(file_ptr);
}
}
return 0;
}
/*????????????????????????????????????????????????????????????-*/
/* This function computes the average power in a specified */
/* window of a double array. */
double power_w(double *ptr, int n)
{
/* Declare and initialize variables. */
int k;
double xsquare=0;
/* Compute sum of values squared in the array x. */
for (k=0; k<=n-1; k++)
xsquare += *(ptr-k)*(*(ptr-k));
/* Return the average squared value. */
return xsquare/n;
}
Sunday, October 21, 2018
Day 16 10/18/18
Arduino Homework
1. Modify your code so that the potentiometer controls the motor speed.
//Simple Motor Speed Control Program
const int MOTOR=9; //Motor on Digital Pin 9
int POT = A0;
void setup()
{
pinMode (MOTOR, OUTPUT);
}
void loop()
{
analogWrite(MOTOR, analogRead(POT));
}
1. Modify your code so that the potentiometer controls the motor speed.
//Simple Motor Speed Control Program
const int MOTOR=9; //Motor on Digital Pin 9
int POT = A0;
void setup()
{
pinMode (MOTOR, OUTPUT);
}
void loop()
{
analogWrite(MOTOR, analogRead(POT));
}
Day 15 10/16/18
Arduino Homework
1. Modify your program to use the accelerometer as an inclinometer so that it displays the angle that the board is tilted to in degrees. Interface your board so that it displays the output in degrees to your LCD display.
#include <math.h>
#include <LiquidCrystal.h>
#define PI 3.14
unsigned long time;
const int xpin = A2; // x-axis of the accelerometer
const int ypin = A1; // y-axis
const int zpin = A3; // z-axis
int xdata = 0;
int ydata = 0;
float xrad;
float yrad;
float degree;
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
void setup() {
// initialize the serial communications:
Serial.begin(57600);
//Set up the LCD's number of columns and rows:
lcd.begin(16, 2);
//Print a message to the LCD.
lcd.print("Angle");
}
void loop() {
time = millis();
Serial.print(time); //prints time since program started
Serial.print("\t");
// print the sensor values:
xdata = analogRead(xpin);
Serial.print(xdata);
// print a tab between values:
Serial.print("\t");
ydata = analogRead(ypin);
Serial.print(ydata);
// print a tab between values:
Serial.print("\t");
Serial.print(analogRead(zpin));
Serial.println();
xrad = xdata - 322;
yrad = ydata - 322;
degree = (atan2(xrad, yrad) * 180/PI);
lcd.setCursor(0,7);
//Print Current Time
lcd.print(degree);
// delay before next reading:
delay(3);
}
1. Modify your program to use the accelerometer as an inclinometer so that it displays the angle that the board is tilted to in degrees. Interface your board so that it displays the output in degrees to your LCD display.
#include <math.h>
#include <LiquidCrystal.h>
#define PI 3.14
unsigned long time;
const int xpin = A2; // x-axis of the accelerometer
const int ypin = A1; // y-axis
const int zpin = A3; // z-axis
int xdata = 0;
int ydata = 0;
float xrad;
float yrad;
float degree;
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
void setup() {
// initialize the serial communications:
Serial.begin(57600);
//Set up the LCD's number of columns and rows:
lcd.begin(16, 2);
//Print a message to the LCD.
lcd.print("Angle");
}
void loop() {
time = millis();
Serial.print(time); //prints time since program started
Serial.print("\t");
// print the sensor values:
xdata = analogRead(xpin);
Serial.print(xdata);
// print a tab between values:
Serial.print("\t");
ydata = analogRead(ypin);
Serial.print(ydata);
// print a tab between values:
Serial.print("\t");
Serial.print(analogRead(zpin));
Serial.println();
xrad = xdata - 322;
yrad = ydata - 322;
degree = (atan2(xrad, yrad) * 180/PI);
lcd.setCursor(0,7);
//Print Current Time
lcd.print(degree);
// delay before next reading:
delay(3);
}
Sunday, October 14, 2018
day 14 10/11/18
Arduino LCD with I^2C Temp Sensor
#1. Interface your I2C temperature to the Arduino and have the values of the temperature shown on the screen. Allow the user to press one of the buttons and have it display the temperature in o F and the other button to display it in oC.
//LCD text with incrementing number
//Include the library code:
#include <LiquidCrystal.h>
#include <Wire.h>
const int temp_address = 73; //1001100 written as decimal number
int c = 0, f = 0;
//Start the time at 0
int time = 0;
//Initialize the library with the numbers of the interface pins
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
void setup() {
lcd.begin(16,2);
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
Wire.begin();
}
void loop() {
lcd.setCursor(0,1);
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// print out the value you read:
Serial.println(sensorValue);
//Send a request
//Start talking to the device at the specified address
Wire.beginTransmission(temp_address);
//Send a bit asking for register zero, the data register
Wire.write(0);
//Complete Transmission
Wire.endTransmission();
//Read the temperature from the device
//Request 1 Byte from the specified address
Wire.requestFrom(temp_address, 1);
//Wait for response
while(Wire.available() == 0);
//Get the temp and read it into a variable
c = Wire.read();
//Do some math to convert the Celsius to Fahrenheit
f = round(c*9.0/5.0 +32.0);
//Send the temperature in degrees C and F to the serial monitor
Serial.print(c);
Serial.print("C ");
Serial.print(f);
Serial.print("F ");
delay(500);
if(sensorValue >= 477 && sensorValue < 719){
lcd.print(f);
lcd.print("f ");
int val = 1;
while (val == 1){
sensorValue = analogRead(A0);
delay(100);
if(sensorValue >= 719 && sensorValue < 1023){
val --;
}
}
}
else if(sensorValue >= 719 && sensorValue <= 1023){
lcd.print(c);
lcd.print("c ");
}
delay(1); // delay in between reads
}
#1. Interface your I2C temperature to the Arduino and have the values of the temperature shown on the screen. Allow the user to press one of the buttons and have it display the temperature in o F and the other button to display it in oC.
//LCD text with incrementing number
//Include the library code:
#include <LiquidCrystal.h>
#include <Wire.h>
const int temp_address = 73; //1001100 written as decimal number
int c = 0, f = 0;
//Start the time at 0
int time = 0;
//Initialize the library with the numbers of the interface pins
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
void setup() {
lcd.begin(16,2);
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
Wire.begin();
}
void loop() {
lcd.setCursor(0,1);
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// print out the value you read:
Serial.println(sensorValue);
//Send a request
//Start talking to the device at the specified address
Wire.beginTransmission(temp_address);
//Send a bit asking for register zero, the data register
Wire.write(0);
//Complete Transmission
Wire.endTransmission();
//Read the temperature from the device
//Request 1 Byte from the specified address
Wire.requestFrom(temp_address, 1);
//Wait for response
while(Wire.available() == 0);
//Get the temp and read it into a variable
c = Wire.read();
//Do some math to convert the Celsius to Fahrenheit
f = round(c*9.0/5.0 +32.0);
//Send the temperature in degrees C and F to the serial monitor
Serial.print(c);
Serial.print("C ");
Serial.print(f);
Serial.print("F ");
delay(500);
if(sensorValue >= 477 && sensorValue < 719){
lcd.print(f);
lcd.print("f ");
int val = 1;
while (val == 1){
sensorValue = analogRead(A0);
delay(100);
if(sensorValue >= 719 && sensorValue < 1023){
val --;
}
}
}
else if(sensorValue >= 719 && sensorValue <= 1023){
lcd.print(c);
lcd.print("c ");
}
delay(1); // delay in between reads
}
Thursday, October 11, 2018
day 13 10/9/18
Elevation problem
Modify the program to determine the following information for a grid of elevation data:
1. Print a count of the number of peaks in the grid.
2. Print the location of valleys instead of peaks. Assume that a valley is a point with an elevation lower than the four surrounding elevations.
3. Find and print the location and elevation of the highest point and the lowest point in the elevation data.
4. Assuming that the distance between points in a vertical and horizontal direction is 100 feet, give the location of the peaks in feet from the lower left corner of the grid.
5. Use all eight neighboring points, instead of only four neighboring points, to determine a peak.
/* This program determines the locations of peaks in an */
/* grid of elevation data. */
#include <stdio.h>
#include <math.h>
#define N 25
#define FILENAME "grid1.txt"
int main(void)
{
/* Declare variables. */
int nrows, ncols, i, j, sum = 0, sum2 = 0, Max = 0, Min = 0, x = 0, y = 0;
double elevation[N][N], distance = 0.;
FILE*grid;
/* Read information from a data file. */
grid = fopen(FILENAME,"r");
if (grid == NULL)
printf("Error opening input file\n");
else
{
fscanf(grid,"%d %d",&nrows,&ncols);
for (i=0; i<=nrows-1; i++){
for (j=0; j<=ncols-1; j++){
fscanf(grid,"%lf",&elevation[i][j]);
}
}
/* Determine and print peak locations. */
printf("Top left point defined as row 0, column 0 \n");
for (i=1; i<=nrows-2; i++){
for (j=1; j<=ncols-2; j++){
if ((elevation[i-1][j]<elevation[i][j]) && (elevation[i+1][j]<elevation[i][j]) && (elevation[i][j-1]<elevation[i][j]) && (elevation[i][j+1]<elevation[i][j]) && (elevation[i-1][j-1]<elevation[i][j]) && (elevation[i+1][j+1]<elevation[i][j]) && (elevation[i+1][j-1]<elevation[i][j]) && (elevation[i-1][j+1]<elevation[i][j])){
printf("Peak at row: %d column: %d \n",i,j);
distance = sqrt((((j+1)*100)*((j+1)*100))+(((nrows-i)*100)*((nrows-i)*100)));
printf("The distance from the peak to the origin is %5.2f feet\n", distance);
sum += 1;
}
}
}
for (i=1; i<=nrows-2; i++){
for (j=1; j<=ncols-2; j++){
if ((elevation[i-1][j]>elevation[i][j]) && (elevation[i+1][j]>elevation[i][j]) && (elevation[i][j-1]>elevation[i][j]) && (elevation[i][j+1]>elevation[i][j])){
printf("Valley at row: %d column: %d \n",i,j);
sum2 += 1;
}
}
}
for (i=1; i<=nrows-1; i++){
for (j=0; j<=ncols-1; j++){
if (elevation[i][j] > Max){
Max = elevation[i][j];
x = i;
y = j;
}
}
}
printf("The max elevation is %d at row: %d column: %d\n", Max, x, y);
Min = elevation[1][0];
for (i=1; i<=nrows-1; i++){
for (j=0; j<=ncols-1; j++){
if (Min > elevation[i][j]){
Min = elevation[i][j];
x = i;
y = j;
}
}
}
printf("The min elevation is %d at row: %d column: %d\n", Min, x, y);
printf("The total amount of Peaks is %d\n", sum);
printf("The total amount of Valleys is %d\n", sum2);
fclose(grid); /* Close file. */
}
return 0; /* Exit program. */
}
Arduino isquaredc temp sensor hw
Modify the program to determine the following information for a grid of elevation data:
1. Print a count of the number of peaks in the grid.
2. Print the location of valleys instead of peaks. Assume that a valley is a point with an elevation lower than the four surrounding elevations.
3. Find and print the location and elevation of the highest point and the lowest point in the elevation data.
4. Assuming that the distance between points in a vertical and horizontal direction is 100 feet, give the location of the peaks in feet from the lower left corner of the grid.
5. Use all eight neighboring points, instead of only four neighboring points, to determine a peak.
/* This program determines the locations of peaks in an */
/* grid of elevation data. */
#include <stdio.h>
#include <math.h>
#define N 25
#define FILENAME "grid1.txt"
int main(void)
{
/* Declare variables. */
int nrows, ncols, i, j, sum = 0, sum2 = 0, Max = 0, Min = 0, x = 0, y = 0;
double elevation[N][N], distance = 0.;
FILE*grid;
/* Read information from a data file. */
grid = fopen(FILENAME,"r");
if (grid == NULL)
printf("Error opening input file\n");
else
{
fscanf(grid,"%d %d",&nrows,&ncols);
for (i=0; i<=nrows-1; i++){
for (j=0; j<=ncols-1; j++){
fscanf(grid,"%lf",&elevation[i][j]);
}
}
/* Determine and print peak locations. */
printf("Top left point defined as row 0, column 0 \n");
for (i=1; i<=nrows-2; i++){
for (j=1; j<=ncols-2; j++){
if ((elevation[i-1][j]<elevation[i][j]) && (elevation[i+1][j]<elevation[i][j]) && (elevation[i][j-1]<elevation[i][j]) && (elevation[i][j+1]<elevation[i][j]) && (elevation[i-1][j-1]<elevation[i][j]) && (elevation[i+1][j+1]<elevation[i][j]) && (elevation[i+1][j-1]<elevation[i][j]) && (elevation[i-1][j+1]<elevation[i][j])){
printf("Peak at row: %d column: %d \n",i,j);
distance = sqrt((((j+1)*100)*((j+1)*100))+(((nrows-i)*100)*((nrows-i)*100)));
printf("The distance from the peak to the origin is %5.2f feet\n", distance);
sum += 1;
}
}
}
for (i=1; i<=nrows-2; i++){
for (j=1; j<=ncols-2; j++){
if ((elevation[i-1][j]>elevation[i][j]) && (elevation[i+1][j]>elevation[i][j]) && (elevation[i][j-1]>elevation[i][j]) && (elevation[i][j+1]>elevation[i][j])){
printf("Valley at row: %d column: %d \n",i,j);
sum2 += 1;
}
}
}
for (i=1; i<=nrows-1; i++){
for (j=0; j<=ncols-1; j++){
if (elevation[i][j] > Max){
Max = elevation[i][j];
x = i;
y = j;
}
}
}
printf("The max elevation is %d at row: %d column: %d\n", Max, x, y);
Min = elevation[1][0];
for (i=1; i<=nrows-1; i++){
for (j=0; j<=ncols-1; j++){
if (Min > elevation[i][j]){
Min = elevation[i][j];
x = i;
y = j;
}
}
}
printf("The min elevation is %d at row: %d column: %d\n", Min, x, y);
printf("The total amount of Peaks is %d\n", sum);
printf("The total amount of Valleys is %d\n", sum2);
fclose(grid); /* Close file. */
}
return 0; /* Exit program. */
}
Arduino isquaredc temp sensor hw
Sunday, October 7, 2018
day 12 10/4/18
Sweeping Servo Distance Sensor
#include <Servo.h>
const int SERVO = 9;
const int IR = A0;
Servo myServo;
int dist1 = 0;
int val = 0;
void setup() {
myServo.attach(SERVO);
Serial.begin(9600);
}
void loop() {
for(int i = 0; i <= 180; i++){
dist1 = readDistance(i);
if (dist1 >= 100){
val++;
}
while (val == 1){
dist1 = analogRead(IR);
dist1 = map(dist1, 50, 500, 0, 255);
dist1 = constrain(dist1, 0, 255);
Serial.println(dist1);
//myServo.write(i);
if (dist1 <= 100){
val--;
}
}
}
delay(50);
for(int i = 180; i >= 0; i--){
dist1 = readDistance(i);
if (dist1 >= 100){
val++;
}
while (val == 1){
dist1 = analogRead(IR);
dist1 = map(dist1, 50, 500, 0, 255);
dist1 = constrain(dist1, 0, 255);
Serial.println(dist1);
//myServo.write(i);
if (dist1 <= 100){
val--;
}
}
}
delay(50);
}
int readDistance(int pos){
myServo.write(pos);
delay(25);
int dist = analogRead(IR);
dist = map(dist, 50, 500, 0, 255);
dist = constrain(dist, 0, 255);
Serial.println(dist);
return dist;
}
#include <Servo.h>
const int SERVO = 9;
const int IR = A0;
Servo myServo;
int dist1 = 0;
int val = 0;
void setup() {
myServo.attach(SERVO);
Serial.begin(9600);
}
void loop() {
for(int i = 0; i <= 180; i++){
dist1 = readDistance(i);
if (dist1 >= 100){
val++;
}
while (val == 1){
dist1 = analogRead(IR);
dist1 = map(dist1, 50, 500, 0, 255);
dist1 = constrain(dist1, 0, 255);
Serial.println(dist1);
//myServo.write(i);
if (dist1 <= 100){
val--;
}
}
}
delay(50);
for(int i = 180; i >= 0; i--){
dist1 = readDistance(i);
if (dist1 >= 100){
val++;
}
while (val == 1){
dist1 = analogRead(IR);
dist1 = map(dist1, 50, 500, 0, 255);
dist1 = constrain(dist1, 0, 255);
Serial.println(dist1);
//myServo.write(i);
if (dist1 <= 100){
val--;
}
}
}
delay(50);
}
int readDistance(int pos){
myServo.write(pos);
delay(25);
int dist = analogRead(IR);
dist = map(dist, 50, 500, 0, 255);
dist = constrain(dist, 0, 255);
Serial.println(dist);
return dist;
}
Wednesday, October 3, 2018
Day 11 10/2/18
Arduino homework
1. Interface your servo with the arduino according to the directions in the previous lab. Allow the user to enter an angle and the servo turns to that angle. If the angle entered is invalid a red light should light on the breadboard.
#include <Servo.h>
const int SERVO = 9;
const int RLED = 10;
const int GLED = 11;
int servoval = 0;
int val = 0;
Servo Servo;
void setup()
{
Serial.begin(9600);
pinMode(RLED, OUTPUT);
pinMode(GLED, OUTPUT);
Servo.attach(SERVO);
Serial.println("Enter servo degree value between 0 and 180");
digitalWrite(GLED, HIGH);
digitalWrite(RLED, LOW);
}
void loop()
{
//Keep working as long as data is in the buffer
while (Serial.available() > 0)
{
servoval = Serial.parseInt();
if (Serial.read() == '\n') //Done transmitting
{
//set servo
if (servoval <= 180 && servoval >= 0){
Serial.println(servoval);
digitalWrite(GLED, HIGH);
digitalWrite(RLED, LOW);
Servo.write(servoval);
}
else {
Serial.println("Not a value between 0 and 180, try again");
val++;
while (val == 1){
digitalWrite(RLED, HIGH);
digitalWrite(GLED, LOW);
delay(150);
digitalWrite(RLED, LOW);
delay(150);
servoval = Serial.parseInt();
if (Serial.read() == '\n'){//Done transmitting
if (servoval <= 180 && servoval >= 0){
Serial.println(servoval);
digitalWrite(GLED, HIGH);
digitalWrite(RLED, LOW);
Servo.write(servoval);
val--;
}
}
}
}
}
}
}
Balloon programming problems
a. Write a program that will print a table of the altitude and the velocity for this weather balloon using units of meters and meters per second. Let the user enter the start time, the increment in time between lines of the table, and the ending time, where all the time values must be less than 48 hours. Use the program to generate a table showing the weather balloon information every 10 minutes over a 2-hour period, starting 4 hours after the balloon was launched.
b. Modify the program above so that it also prints the peak altitude and its corresponding time.
c. Modify the program so that it will check to be sure that the final time is greater than the initial time. If it is not, ask the user to reenter the complete set of report information.
d. The preceding equations are accurate only for the time from 0 to 48 hours, so modify the program generated above so that it prints a message to the user that specifies an upper bound of 48 hours. Also, check the user input to make sure that it stays within the proper bounds. If there are errors, ask the user to reenter the complete set of report information.
e. Modify the program above so that it stores the time, altitude, and velocity information in a data file named .
#include <stdio.h>
#include <math.h>
#define FILENAME "ballon1.txt"
double starttime, endtime, timeincr, t, altitude1, velocity, maxwave = 0, maxwavetime = 0;
char minorhour;
int main(void){
FILE *balloon;
balloon = fopen(FILENAME,"w");
_Bool keep_looping = 1;
_Bool keep_looping2 = 1;
_Bool keep_looping3 = 1;
printf("This program will print a table of the altitudes and velocities of a weather balloon at a given time interval in hours (within 48)\n");
while (keep_looping == 1){
while (keep_looping2 == 1){
printf("Enter a start time\n");
scanf("%lf",&starttime);
if(starttime < 0){
printf("The start time cannot be negative,\nplease reenter all credentials\n\n");
}
if(starttime >= 48){
printf("The start time cannot be equal to or over 48,\nplease reenter all credentials\n\n");
}
if(starttime >= 0 && starttime < 48){
keep_looping2 = 0;
}
}
printf("\nEnter an end time\n");
scanf("%lf",&endtime);
if(starttime > endtime){
printf("The start time cannot be after the end time,\nplease reenter all credentials\n\n");
keep_looping2 = 1;
}
if(starttime == endtime){
printf("The start time cannot equal the end time,\nplease reenter all credentials\n\n");
keep_looping2 = 1;
}
if(endtime < 0){
printf("the end time cannot be negative,\nplease reenter all credentials\n\n");
}
if(endtime >48){
printf("the end time cannot be over 48 hours,\nplease reenter all credentials\n\n");
}
if(starttime < endtime && endtime > 0 && endtime <= 48){
keep_looping = 0;
}
}
printf("\nEnter a time increment\n");
scanf("%lf",&timeincr);
while (keep_looping3 == 1){
printf("Please specify if it is in minutes or hour (m or h)\n");
scanf(" %c",&minorhour);
if(minorhour != 109 || minorhour != 77 || minorhour != 104 || minorhour != 72){
printf("time interval must be in either minutes or hours (m or h),\nplease reenter all credentials\n\n");
}
if(minorhour == 109 || minorhour == 77 || minorhour == 104 || minorhour == 72){
keep_looping3 = 0;
}
}
printf("Altitudes (in meters):\n");
if(minorhour == 109 || minorhour == 77){
timeincr = timeincr / 60;
}
int timedivider = (endtime-starttime) / timeincr;
int time[100], velocity[100], altitude[100];
fprintf(balloon, "Altitudes:\n");
for (t = starttime; t <= endtime; t = t + timeincr){
int i = 0;
altitude[i] = (-.12 * pow(t,4)) + (12 * pow(t,3)) - (380 * pow(t,2)) + (4100 * t) + 220;
altitude1 = (-.12 * pow(t,4)) + (12 * pow(t,3)) - (380 * pow(t,2)) + (4100 * t) + 220;
printf("%d\n", altitude[i]);
fprintf(balloon, "%d\n", altitude[i]);
if (altitude1 >maxwave){
maxwave = altitude1;
maxwavetime = t;
}
i++;
}
fprintf(balloon, "Velocities:\n");
printf("Velocities (in meters per second):\n");
for (t = starttime; t <= endtime; t = t + timeincr){
int j = 0;
velocity[j] = (-.48 * pow(t,3)) + (36 * pow(t,2)) - (760 * t) + 4100;
printf("%d\n", velocity[j]);
fprintf(balloon, "%d\n", velocity[j]);
j++;
}
fprintf(balloon, "Times:\n");
printf("times:\n");
for (t = starttime; t <= endtime; t = t + timeincr){
int h = 0;
time[h] = t;
printf("%d\n", time[h]);
fprintf(balloon, "%d\n", time[h]);
h++;
}
/*fprintf(balloon, "Altitude Velocity Time\n");
for (int k = 0; k <= timedivider; k++){
fprintf(balloon, "%d %d %d\n", altitude[k], velocity[k], time[k]);
}*/
printf("the peak altitude was %f meters at time %f hours", maxwave, maxwavetime);
fclose(balloon);
return 0;
}
1. Interface your servo with the arduino according to the directions in the previous lab. Allow the user to enter an angle and the servo turns to that angle. If the angle entered is invalid a red light should light on the breadboard.
#include <Servo.h>
const int SERVO = 9;
const int RLED = 10;
const int GLED = 11;
int servoval = 0;
int val = 0;
Servo Servo;
void setup()
{
Serial.begin(9600);
pinMode(RLED, OUTPUT);
pinMode(GLED, OUTPUT);
Servo.attach(SERVO);
Serial.println("Enter servo degree value between 0 and 180");
digitalWrite(GLED, HIGH);
digitalWrite(RLED, LOW);
}
void loop()
{
//Keep working as long as data is in the buffer
while (Serial.available() > 0)
{
servoval = Serial.parseInt();
if (Serial.read() == '\n') //Done transmitting
{
//set servo
if (servoval <= 180 && servoval >= 0){
Serial.println(servoval);
digitalWrite(GLED, HIGH);
digitalWrite(RLED, LOW);
Servo.write(servoval);
}
else {
Serial.println("Not a value between 0 and 180, try again");
val++;
while (val == 1){
digitalWrite(RLED, HIGH);
digitalWrite(GLED, LOW);
delay(150);
digitalWrite(RLED, LOW);
delay(150);
servoval = Serial.parseInt();
if (Serial.read() == '\n'){//Done transmitting
if (servoval <= 180 && servoval >= 0){
Serial.println(servoval);
digitalWrite(GLED, HIGH);
digitalWrite(RLED, LOW);
Servo.write(servoval);
val--;
}
}
}
}
}
}
}
Balloon programming problems
a. Write a program that will print a table of the altitude and the velocity for this weather balloon using units of meters and meters per second. Let the user enter the start time, the increment in time between lines of the table, and the ending time, where all the time values must be less than 48 hours. Use the program to generate a table showing the weather balloon information every 10 minutes over a 2-hour period, starting 4 hours after the balloon was launched.
b. Modify the program above so that it also prints the peak altitude and its corresponding time.
c. Modify the program so that it will check to be sure that the final time is greater than the initial time. If it is not, ask the user to reenter the complete set of report information.
d. The preceding equations are accurate only for the time from 0 to 48 hours, so modify the program generated above so that it prints a message to the user that specifies an upper bound of 48 hours. Also, check the user input to make sure that it stays within the proper bounds. If there are errors, ask the user to reenter the complete set of report information.
e. Modify the program above so that it stores the time, altitude, and velocity information in a data file named .
#include <stdio.h>
#include <math.h>
#define FILENAME "ballon1.txt"
double starttime, endtime, timeincr, t, altitude1, velocity, maxwave = 0, maxwavetime = 0;
char minorhour;
int main(void){
FILE *balloon;
balloon = fopen(FILENAME,"w");
_Bool keep_looping = 1;
_Bool keep_looping2 = 1;
_Bool keep_looping3 = 1;
printf("This program will print a table of the altitudes and velocities of a weather balloon at a given time interval in hours (within 48)\n");
while (keep_looping == 1){
while (keep_looping2 == 1){
printf("Enter a start time\n");
scanf("%lf",&starttime);
if(starttime < 0){
printf("The start time cannot be negative,\nplease reenter all credentials\n\n");
}
if(starttime >= 48){
printf("The start time cannot be equal to or over 48,\nplease reenter all credentials\n\n");
}
if(starttime >= 0 && starttime < 48){
keep_looping2 = 0;
}
}
printf("\nEnter an end time\n");
scanf("%lf",&endtime);
if(starttime > endtime){
printf("The start time cannot be after the end time,\nplease reenter all credentials\n\n");
keep_looping2 = 1;
}
if(starttime == endtime){
printf("The start time cannot equal the end time,\nplease reenter all credentials\n\n");
keep_looping2 = 1;
}
if(endtime < 0){
printf("the end time cannot be negative,\nplease reenter all credentials\n\n");
}
if(endtime >48){
printf("the end time cannot be over 48 hours,\nplease reenter all credentials\n\n");
}
if(starttime < endtime && endtime > 0 && endtime <= 48){
keep_looping = 0;
}
}
printf("\nEnter a time increment\n");
scanf("%lf",&timeincr);
while (keep_looping3 == 1){
printf("Please specify if it is in minutes or hour (m or h)\n");
scanf(" %c",&minorhour);
if(minorhour != 109 || minorhour != 77 || minorhour != 104 || minorhour != 72){
printf("time interval must be in either minutes or hours (m or h),\nplease reenter all credentials\n\n");
}
if(minorhour == 109 || minorhour == 77 || minorhour == 104 || minorhour == 72){
keep_looping3 = 0;
}
}
printf("Altitudes (in meters):\n");
if(minorhour == 109 || minorhour == 77){
timeincr = timeincr / 60;
}
int timedivider = (endtime-starttime) / timeincr;
int time[100], velocity[100], altitude[100];
fprintf(balloon, "Altitudes:\n");
for (t = starttime; t <= endtime; t = t + timeincr){
int i = 0;
altitude[i] = (-.12 * pow(t,4)) + (12 * pow(t,3)) - (380 * pow(t,2)) + (4100 * t) + 220;
altitude1 = (-.12 * pow(t,4)) + (12 * pow(t,3)) - (380 * pow(t,2)) + (4100 * t) + 220;
printf("%d\n", altitude[i]);
fprintf(balloon, "%d\n", altitude[i]);
if (altitude1 >maxwave){
maxwave = altitude1;
maxwavetime = t;
}
i++;
}
fprintf(balloon, "Velocities:\n");
printf("Velocities (in meters per second):\n");
for (t = starttime; t <= endtime; t = t + timeincr){
int j = 0;
velocity[j] = (-.48 * pow(t,3)) + (36 * pow(t,2)) - (760 * t) + 4100;
printf("%d\n", velocity[j]);
fprintf(balloon, "%d\n", velocity[j]);
j++;
}
fprintf(balloon, "Times:\n");
printf("times:\n");
for (t = starttime; t <= endtime; t = t + timeincr){
int h = 0;
time[h] = t;
printf("%d\n", time[h]);
fprintf(balloon, "%d\n", time[h]);
h++;
}
/*fprintf(balloon, "Altitude Velocity Time\n");
for (int k = 0; k <= timedivider; k++){
fprintf(balloon, "%d %d %d\n", altitude[k], velocity[k], time[k]);
}*/
printf("the peak altitude was %f meters at time %f hours", maxwave, maxwavetime);
fclose(balloon);
return 0;
}
Monday, October 1, 2018
Day 9 9/25/18
1. Complete the random number problem but with all four parts;
a. Write a program that uses the rand_float function developed previously to generate sequences of
random floating-point values between 4 and 10. Then compare the computed mean and variance with
the computed theoretical values. As you use more and more random numbers, the computed values
and the theoretical values should become closer.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define seed 26
#define number 10
#define npts 10
int a=4, b=10, list, sum, sumlist, average, variance, xna, xna2;
float random_float[number];
float rand_float(int a,int b);
int main(void)
{
srand(seed);
printf("list of %d random numbers:\n", number);
for (int i=1; i<=number; i++){
random_float[i] = rand_float(a,b);
list = random_float[i];
printf("%d\n", list);
sum +=list;}
average = sum / number;
for(int i=1; i<=number; i++){
xna = random_float[i] - average;
xna2 = pow(xna, 2);
sumlist += xna2;
}
variance = sumlist / (number-1);
printf("Average is:\n%d\nVariance is:\n%d\n", average, variance);
/* Exit program. */
return 0;
}
float rand_float(int a,int b)
{
return rand()%(b-a+1) + a;
}
Wednesday, September 19, 2018
day 7 9/18/18
Random dice problem and factorial approximation problem
#1
Write a program to simulate an experiment rolling two six-sided “fair” dice. Allow the user to enter the number of rolls of the dice to simulate. What percentage of the time does the sum of the dots on the dice equal 8 in the simulation?
ANSWER:
about 8% which includes combinations (2,6), (3,5), (4,4), (5,3), (6,2) out of 72 combinations
#2
A convenient approximation for computing the factorial n! for large values of n is given by the Stirling formula: Write an integer function for computing this approximation to a factorial. Assume that the corresponding prototype is int n_fact(int n);
#1
Write a program to simulate an experiment rolling two six-sided “fair” dice. Allow the user to enter the number of rolls of the dice to simulate. What percentage of the time does the sum of the dots on the dice equal 8 in the simulation?
ANSWER:
about 8% which includes combinations (2,6), (3,5), (4,4), (5,3), (6,2) out of 72 combinations
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
/* Declare variables and function prototype. */
unsigned int seed;
int a=1, b=6, sum, dice1, dice2, k;
int rand_int(int a,int b);
/* Get seed value and interval limits. */
printf("Enter a positive integer seed value: \n");
scanf("%u",&seed);
srand(seed);
//printf("Enter integer limits a and b (a<b): \n");
//scanf("%i %i",&a,&b);
printf("Enter the amount of times to roll the dice: \n");
scanf("%i", &k);
/* Generate and print ten random numbers. */
for (int i=1; i<=k; i++){
dice1 = rand_int(a,b);
dice2 = rand_int(a,b);
printf("Random dice number 1: \n");
printf("%i ",dice1);
printf("\n");
printf("Random dice number 2: \n");
printf("%i ",dice2);
printf("\n");
sum = dice1 + dice2;
printf("the sum of the dice is: %i \n",sum);}
/* Exit program. */
return 0;
}
/* This function generates a random integer */
/* between specified limits a and b (a<b). */
int rand_int(int a,int b)
{
return rand()%(b-a+1) + a;
}
A convenient approximation for computing the factorial n! for large values of n is given by the Stirling formula: Write an integer function for computing this approximation to a factorial. Assume that the corresponding prototype is int n_fact(int n);
/* This program compares a recursive function and */
/* a nonrecursive function for computing factorials. */
#include <stdio.h>
#include <math.h>
#define PI 3.1415
#define e 2.7182
int main(void)
{
/* Declare variables and function prototypes. */
int n;
double factorial(int k);
double factorial_r(int k);
int n_fact(int n);
/* Get user input. */
printf("Enter positive integer: \n");
scanf("%i",&n);
/* Compute and print factorials. */
printf("sterling formula for the factorial: %i! = %i",n,n_fact(n));
//printf("Nonrecursive: %i! = %f \n",n,factorial(n));
//printf("Recursive: %i! = %f \n",n,factorial_r(n));
/* Exit program. */
return 0;
}
int n_fact(int n){
n = ceil((sqrt(2*PI*n))*(pow((n/e),n)));
return n;
}
Arduino speaker and servo/PIR sensor
#1
Combine your servo and your PIR sensor. Tape a large cardboard arrow on top of the servo. When
someone walks into the room, have the servo point a sign that reads "occupied". When no person is
detected, have the servo point to a sign that says "empty" If you wish to be more creative and use
something other than an arrow and have other signs that is great!
I developed 2 programs one where the sensor is triggered once and the servo moves from unoccupied
to occupied and back when the sensor is triggered only once; the other program is triggered once and
moves from unoccupied to occupied and needs to be triggered again to go back to unoccupied.
the first one
#include <Servo.h>
const int SERVO=9; //Servo on Pin 9
const int PIR=2;
Servo myServo;
int val = 0; //for storing the reading from the POT
void setup()
{
pinMode (PIR, INPUT);
myServo.attach(SERVO);
Serial.begin(9600);
}
void loop()
{
if (digitalRead(PIR) == HIGH)
{
myServo.write(80);
Serial.println("occupied");
delay(500);
}
else if (digitalRead(PIR) == LOW)
{
myServo.write(0);
Serial.println("unoccupied");
delay(500);
}
}
the second one
#include <Servo.h>
const int SERVO=9; //Servo on Pin 9
const int PIR=2;
Servo myServo;
int val = 1;
void setup()
{
pinMode (PIR, INPUT);
myServo.attach(SERVO);
Serial.begin(9600);
}
void loop()
{
while (val == 1)
{
if (digitalRead(PIR) == HIGH)
{
myServo.write(80);
Serial.println("triggered");
delay(2000);
val++;
Serial.println(val);
while (val == 2)
{
Serial.println("occupied");
if (digitalRead(PIR) == HIGH)
{
myServo.write(0);
delay(500);
val--;
Serial.println(val);
}
}
}
val--;
}
if (digitalRead(PIR) == LOW)
{
myServo.write(0);
Serial.println("unoccupied");
delay(500);
val++;
}
Serial.println(val);
}
#2
See if you can modify this program to play a simple song.
I made when you wish upon a star
const int kSpkr = 9;
#define NOTE_C4 262
#define NOTE_D4 294
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_F45 370
#define NOTE_G4 392
#define NOTE_A4 440
#define NOTE_Bb4 466
#define NOTE_B4 494
#define NOTE_C5 523
#define NOTE_D5 587
#define NOTE_E5 659
#define NOTE_F5 698
#define NOTE_G5 784
#define NOTE_C6 1047
void setup() {
pinMode(kSpkr, OUTPUT);
}
void loop() {
tone(kSpkr, NOTE_C4, 500);
delay(500);
tone(kSpkr, NOTE_C5, 500);
delay(500);
tone(kSpkr, NOTE_Bb4, 500);
delay(500);
tone(kSpkr, NOTE_A4, 500);
delay(500);
tone(kSpkr, NOTE_F45, 500);
delay(500);
tone(kSpkr, NOTE_G4, 500);
delay(500);
tone(kSpkr, NOTE_D5, 1000);
delay(500);
noTone(kSpkr);
delay(50);
tone(kSpkr, NOTE_E4, 500);
delay(500);
tone(kSpkr, NOTE_E5, 500);
delay(500);
tone(kSpkr, NOTE_D5, 500);
delay(500);
tone(kSpkr, NOTE_C5, 500);
delay(500);
tone(kSpkr, NOTE_B4, 500);
delay(500);
tone(kSpkr, NOTE_C5, 500);
delay(500);
tone(kSpkr, NOTE_F5, 1000);
delay(500);
noTone(kSpkr);
delay(50);
tone(kSpkr, NOTE_G5, 500);
delay(500);
tone(kSpkr, NOTE_F5, 500);
delay(550);
tone(kSpkr, NOTE_E5, 500);
delay(550);
tone(kSpkr, NOTE_D5, 500);
delay(550);
tone(kSpkr, NOTE_C5, 500);
delay(550);
tone(kSpkr, NOTE_Bb4, 550);
delay(600);
tone(kSpkr, NOTE_A4, 600);
delay(650);
tone(kSpkr, NOTE_G4, 650);
delay(700);
tone(kSpkr, NOTE_D5, 700);
delay(750);
tone(kSpkr, NOTE_G5, 700);
delay(750);
tone(kSpkr, NOTE_C6, 1500);
delay(2000);
}
Monday, September 17, 2018
day 6 9/13/18
Great Circle Distance Problems
#1,2,3,4,and5
#1,2,3,4,and5
#include <stdio.h>
#include <math.h>
#define PI 3.141593
double angle(double, double, double, double, double, double);
int main(void)
{
/* Declare variables and function prototype. */
double lat1, long1, lat2, long2;
char direction, direction2, direction3, direction4;
double gc_distance(double lat1,double long1,
double lat2,double long2);
/* Get locations of two points. */
printf("Enter latitude and longitude west ");
printf("for location 1: \n");
scanf("%lf %lf",&lat1,&long1);
printf("is the latitude N or S\n");
scanf(" %c", &direction);
printf("is the longitude W or E\n");
scanf(" %c", &direction3);
printf("Enter latitude and longitude west ");
printf("for location 2: \n");
scanf("%lf %lf",&lat2,&long2);
printf("is the latitude N or S\n");
scanf(" %c", &direction2);
printf("is the longitude W or E\n");
scanf(" %c", &direction4);
if(direction==78){
lat1 = lat1*1;
}
else if(direction==83){
lat1 = lat1*-1;
}
if(direction2==78){
lat2 = lat2*1;
}
else if(direction2==83){
lat2 = lat2*-1;
}
if(direction3==69){
long1 = 360 - long1;
}
else if(direction3==87){
long1 = long1*1;
}
if(direction4==69){
long2 = 360 - long2;
}
else if(direction4==87){
long2 = long2*1;
}
/* Print great circle distance. */
printf("Great Circle Distance: %.0f miles \n",
gc_distance(lat1,long1,lat2,long2));
/* Exit program. */
return 0;
}
/* This function computes the distance between two */
/* points using great circle distances. */
double gc_distance(double lat1,double long1,
double lat2,double long2)
{
/* Declare variables. */
double rho, phi, theta, gamma, x, y, z, X, Y, Z;
/* Convert latitude,longitude to rectangular coordinates. */
rho = 3960;
phi = (90 - lat1)*(PI/180.0);
theta = (360 - long1)*(PI/180.0);
x = rho*sin(phi)*cos(theta);
y = rho*sin(phi)*sin(theta);
z = rho*cos(phi);
phi = (90 - lat2)*(PI/180.0);
theta = (360 - long2)*(PI/180.0);
X = rho*sin(phi)*cos(theta);
Y = rho*sin(phi)*sin(theta);
Z = rho*cos(phi);
/* Compute angle between vectors. */
gamma = angle(x,y,z,X,Y,Z);
/* Compute and return great circle distance. */
return gamma*rho;
}
double angle(double x1, double y1, double z1, double x2, double y2, double z2){
double dot, dist1, dist2, gamma;
dot = x1*x2 + y1*y2 + z1*z2;
dist1 = sqrt(x1*x1 + y1*y1 + z1*z1);
dist2 = sqrt(x2*x2 + y2*y2 + z2*z2);
gamma = acos(dot/(dist1*dist2));
return gamma;
}
Arduino Light and Motion Sensor
CLASSWORK
This program senses the amount of light coming into the sensor and as the sensor is
covered into darkness it illuminates the rgb more and more.
const int RLED=9; //Red LED on pin 9 (PWM)
const int LIGHT=A0; //Lght Sensor on analog pin 0
const int MIN_LIGHT=200; //Minimum expected light value
const int MAX_LIGHT=900; //Maximum Expected Light value
int val = 0; //variable to hold the analog reading
void setup()
{
pinMode(RLED, OUTPUT); //Set LED pin as output
Serial.begin(9600);
}
void loop()
{
val = analogRead(LIGHT); //Read the light sensor
val = map(val, MIN_LIGHT, MAX_LIGHT, 255, 0);//Map the light reading
val = constrain(val, 0, 255); //Constrain light value
analogWrite(RLED, val); //Control the LED
Serial.println(val);
}
HOMEWORK
Connect your PIR sensor and your CdS cell(light sensor). The PIR and CdS sensors will control the LED
behavior as follows:
When the PIR is triggered the LED is on.
When the CdS is uncovered and the PIR sensor is untriggered, the LED is off.
When the CdS cell is covered and the PIR sensor is off, the LED blinks.
const int LED=9;
const int PIR=2;
const int LIGHT=A0; //Lght Sensor on analog pin 0
const int MIN_LIGHT=200; //Minimum expected light value
const int MAX_LIGHT=900; //Maximum Expected Light value
int val = 0; //variable to hold the analog
void setup()
{
pinMode (LED, OUTPUT);
pinMode (PIR, INPUT);
Serial.begin(9600);
}
void loop()
{
val = analogRead(LIGHT); //Read the light sensor
val = map(val, MIN_LIGHT, MAX_LIGHT, 255, 0);//Map the light reading
val = constrain(val, 0, 255); //Constrain light value
Serial.println(val);
if (val == 255){
digitalWrite(LED, HIGH);
delay(100);
digitalWrite(LED, LOW);
delay(100);
}
else{
digitalWrite(LED, LOW);
}
if (digitalRead(PIR) == LOW)
{
digitalWrite(LED, LOW);
}
else
{
digitalWrite(LED, HIGH);
}
}
Subscribe to:
Comments (Atom)


