Skip to main content

Day 6: Analog Sensors | Functions and Modularity

Functions

Functions are sets of statements that typically perform operation or compute value. They can help to make programs more accessible and usable for non-programmers e.g. create function that allows user to type "go forward" and move a robot forward.

Modules


-Functions can be split up into modules, "divide and conquer"
-Each module has specific purpose, can be written and tested separately
-Smaller than complete solution, therefore testing is easier
-Can be used in new problem solutions without being retested
-Reduces overall length of program
-Allows for increased collaboration; modules can be worked on in parallel

Debugging Longer Programs


Use a compiler that gives meaningful information about errors. Adding comments around some sections of code can allow for better focus on other parts of the program. Test complicated functions by themselves.

Programmer Defined Functions

Execution of program always begins with main function. Additional functions are called when program encounters function names.

Example 1.1
/* */
/* This program prints 21 values of the sinc */
/* function in the interval [a,b] using */
/* computations within the main function. */
#include <stdio.h>
#include <math.h>
#define PI 3.141593
int main(void)
{
/* Declare variables. */
int k;
double a, b, x_incr, new_x, sinc_x;
/* Get interval endpoints from the user. */
printf("Enter endpoints a and b (a<b): \n");
scanf("%lf %lf",&a,&b);
x_incr = (b - a)/20;
/* Compute and print table of sinc(x) values. */
printf("x and sinc(x) \n");
for (k=0; k<=20; k++)
{
new_x = a + k*x_incr;
if (fabs(new_x) < 0.0001)
sinc_x = 1.0;
else
sinc_x = sin(PI*new_x)/(PI*new_x);
printf("%f %f \n",new_x,sinc_x);
}
/* Exit program. */
return 0;
}

Example 1.2
/* This program prints 21 values of the sinc function */
/* using a programmer-defined function. */
#include <stdio.h>
#include <math.h>
#define PI 3.141593
int main(void)
{
/* Declare variables. */
int k;
double a, b, x_incr, new_x;
double sinc(double x);
/* Get interval endpoints from the user. */
printf("Enter endpoints a and b (a<b): \n");
scanf("%lf %lf",&a,&b);
x_incr = (b - a)/20;
/* Compute and print table of sinc(x) values. */
printf("x and sinc(x) \n");
for (k=0; k<=20; k++)
{
new_x = a + k*x_incr;
printf("%f %f \n",new_x,sinc(new_x));
}
/* Exit program. */
return 0;
}
/* */
/* This function evaluates the sinc function. */
double sinc(double x)
{
if (fabs(x) < 0.0001)
return 1.0;
else
return sin(PI*x)/(PI*x);

}

//Recursive factorial
//This function calculates the factorial for a user-given integer
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(void)
{
  int n;
  //Declare function prototype
  double factorial_r(int k);
  //Ask for user to input integer
  printf("Enter positive integer: \n");
  scanf("%i",&n);
  //Print values
  printf("Recursive: %i!= %d \n",n,factorial_r(n));
  return 0;
}

//Recursive factorial function
double factorial_r(double k)
{
  //Function will continue until k reaches 0
  if(k==0)
  {
    return 1;
  }
  else
  {
    return k*factorial_r(k-1);
  }

}

Homework

Lab

This program utilized a pir sensor and a light sensor. The goal was to have an LED light up every time the pir detected motion, and to do certain actions when it did not detect motion, as noted in the comments in my code. 

//Define pins
const int led=9;
const int cds=A0;
const int pir=2;
int count=0;
int val=0;
boolean currentbutton=LOW;
boolean lastbutton=LOW;
int k=0;

void setup() {
  // put your setup code here, to run once:
  pinMode(led,OUTPUT);
  pinMode(cds,INPUT);
  pinMode(pir,INPUT);
  digitalWrite(led,LOW);
  Serial.begin(9600);
}

//Create debounce function
boolean debounce(boolean last)
{
  boolean current=digitalRead(pir);
  if(last!=current)
  {
    delay(5);
    current=digitalRead(pir);
  }
  return current;
}
void loop() {
  // put your main code here, to run repeatedly:
  //Use debounce function to ensure that it does not continuously count, and increments neatly
  currentbutton=debounce(lastbutton);
  //If the pir is high, the light will turn on, and the count increments by one
  if(lastbutton==LOW && currentbutton==HIGH)
  {
    digitalWrite(led,HIGH);
    count++;
    Serial.print("Count: ");
    Serial.println(count);
  }
  lastbutton=currentbutton;
  //If the pir is low, we will do one of two things depending on the reading of the light sensor
  if(currentbutton==LOW)
  {
    val=analogRead(cds);
    //If the light sensor is uncovered, the reading will be over 300 and therefore I write the led low
    if(val>300 && digitalRead(pir)==LOW)
    {
      digitalWrite(led,LOW);
    }
    //If the light sensor is covered, the reading will be 300 or less
    //I therefore want the led to blink the amount of times the pir has been activated
    if(val<=300 && digitalRead(pir)==LOW)
    {
      //By using a while loop, I can have the code to make the LED blink the amount of times I want it to
      while(k<=count)
      {
        digitalWrite(led,HIGH);
        delay(250);
        digitalWrite(led,LOW);
        delay(250);
        k++;
        //Once I reach the count, I reset k to 0 and write the LED low for 1000 milliseconds to indicate a reset
        if(k==count)
        {
          k=0;
          digitalWrite(led,LOW);
          delay(1000);
          break;
        }
      }
    }
  }
}

Programming

//GPS Distances//
//This program calculates the distance between two GPS coordinates//
#include <stdio.h>
#include <math.h>

//Create function to calculate angle between vectors//
double angle(double x1,double y1,double z1,double x2,double y2,double z2)
{
  double adotb=x1*x2+y1*y2+z1*z2;
  double maga=sqrt(x1*x1+y1*y1+z1*z1);
  double magb=sqrt(x2*x2+y2*y2+z2*z2);
  double angle=acos(adotb/(maga*magb));
  return angle;
}

//Function to calculate distance between two vectors//

float gc_distance(float firstlat, float firstlong, float secondlat, float secondlong){

//Define values//
  float pi=3.14159265;
  float x1, y1, z1, x2, y2 ,z2;
  float phi1,theta1,phi2,theta2;
  float rho=3960;

  //Find angles//
  phi1=(90-firstlat)*pi/180;
  theta1=(360-firstlong)*pi/180;
  phi2=(90-secondlat)*pi/180;
  theta2=(360-secondlong)*pi/180;

  //Find rectangular coordinates//
  x1=rho*sin(phi1)*cos(theta1);
  y1=rho*sin(phi1)*sin(theta1);
  z1=rho*cos(phi1);
  x2=rho*sin(phi2)*cos(theta2);
  y2=rho*sin(phi2)*sin(theta2);
  z2=rho*cos(phi2);

  //Use angle function to find angle between rectangular coordinates//
  //Multiply by radius to find distance//
double ans=3960*angle(x1,y1,z1,x2,y2,z2);
  //Print result
  return ans;
  }
int main(void){
  int lat_val1, long_val1,lat_val2,long_val2;
  float firstlat, firstlong, secondlat, secondlong;

  //Read latitude and longitude for first point//
  printf("Input the latitude and longitude of the first city\n");
  scanf("%f %f",&firstlat,&firstlong);

  //Find out if latitude is north or south and adjust accordingly//
  printf("Is the value of latitude north or south? Enter 1 for north   and 2 for south.\n");
  scanf("%i",&lat_val1);
  if(lat_val1==2)
  {
    firstlat=-firstlat;
  }

  //Find out if longitude is east or west//
  printf("Is the value of longitude east or west? Enter 1 for west   and 2 for east\n");
  scanf("%i",&long_val1);
  if(long_val1==2)
  {
    firstlong=-firstlong;
  }


  //Read latitude and longitude for second point//
  printf("Input the latitude and longitude of the second city\n");
  scanf("%f %f",&secondlat,&secondlong);

  //Find out whether latitude value is north or south and adjust   accordingly//
  printf("Is the value of latitude north or south? Enter 1 for north   and 2 for south.\n");
  scanf("%i",&lat_val2);
  if(lat_val2==2)
  {
     secondlat=-secondlat;
  }

  //Find out whether longitude is east or west//
  printf("Is the value of longitude east or west? Enter 1 for west  and 2 for east\n");
  scanf("%i",&long_val2);
  if(long_val1==2)
  {
    secondlong=-secondlong;
  }

  //Use function to calculate distance//
  float  distance=gc_distance(firstlat,firstlong,secondlat,secondlong);
  printf("Distance: %4.3f miles\n",distance);
  return 0;
}

Comments

Popular posts from this blog

Day 25: Python, Graphing, 3D Visualization and Inertial Measurement

Python Arduino Code int trigPin=13; //Sensor Trig pin connected to Arduino pin 13 int echoPin=11; //Sensor Echo pin connected to Arduino pin 11 float pingTime; //time for ping to travel from sensor to target and return float targetDistance; //Distance to Target in inches float speedOfSound=776.5; //Speed of sound in miles per hour when temp is 77 degrees. void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); } void loop() { // put your main code here, to run repeatedly: digitalWrite(trigPin, LOW); //Set trigger pin low delayMicroseconds(2000); //Let signal settle digitalWrite(trigPin, HIGH); //Set trigPin high delayMicroseconds(15); //Delay in high state digitalWrite(trigPin, LOW); //ping has now been sent delayMicroseconds(10); //Delay in low state pingTime = pulseIn(echoPin, HIGH); //pingTime is presented in microceconds pingTime=pingTime/1000000; //convert pin...

Day 19: Project 2

Our project was a test stand for rocket motors Using an LCD screen, we could choose a display mode, and it would display the selected value. Unfortunately, we were unable to calibrate the pressure sensor, so all we ended up with was a load cell. We used the HX711 library for this. The LCD screen displayed the maximum force experienced during the test Code for MotorSensors.h #ifndef _MOTORSENSORS_ #define _MOTORSENSORS_ #include <LiquidCrystal.h> //Include Liquid Crystal Library #include <HX711.h> //Include HX711 Load Cell library #include "HX711.h" //Include Load Cell header file #include <math.h> //Include math library #define calibration_factor -8815 //set calibration factor #define DAT 3 //define DAT pin #define CLK 2 //define CLK pin #define pressurePin A1 #define tempPin A2 HX711 scale(DAT,CLK);  LiquidCrystal lcd(8,9,4,5,6,7); //Define LCD pins //Initialize variables float maxkg=0;  float currentval=0; float maxforce=0; char mo...