//STAGE #1
//Create variables for:
const int transistor_pin = 2 ; //The pin controlling the Solenoid (Table 1)
const int sensor_pin = A0 ; //The pin attached to the Hall-Effect Sensor (Table 1)]
int voltage = 0 ; //The voltage of the Hall Effect Sensor (as an int)
const float pendulength = 0.3 ; //The pendulum length (as a float )
void setup()
{
// initialize serial communication at 9600 bits per second.
Serial.begin(9600);
//STAGE 2 - pin modes
pinMode(transistor_pin, OUTPUT);
pinMode(sensor_pin, INPUT);
//Control solenoid
digitalWrite(transistor_pin, LOW);
digitalWrite(transistor_pin, HIGH);
delay(500);
digitalWrite(transistor_pin, LOW );
Serial.println("Initialisation complete");
}
//STAGE 3 - the main loop
void loop()
{
//Array for gravity
float gravities[9];
//Variables for timing
unsigned long startTime = 0;
unsigned long currentTime = 0;
unsigned long peakTime = 0;
unsigned long half_T = 0;
//Variable for previous voltage and peak time
int prev_voltage = 0;
unsigned long prev_peakTime = 0;
//Variable for peak counter
int num_peaks = 0;
//get start time
startTime = micros();
//Progress check
Serial.println("Variables assigned");
Serial.print("Gravity array - ");
progress_check(gravities);
do {
//read Hall effects sensor
voltage = analogRead(sensor_pin);
//Identify if peak
if (voltage>=550 && prev_voltage<550) {
//Increment peak counter
num_peaks = num_peaks + 1 ;
//get current time
currentTime = micros();
//Calc time of peak in microseconds
peakTime = currentTime - startTime ;
//Calc half period and gravity (if applicable)
if (num_peaks > 1) {
half_T = peakTime-prev_peakTime;
gravities[num_peaks-2] = gravity_calc(half_T);
//Progress check
progress_check(gravities);
}
Serial.println(); // Move to the next line after printing the array
prev_peakTime = peakTime;
}
prev_voltage = voltage;
//Add delay
delayMicroseconds(50);
} while (num_peaks < 10);
//STAGE 5 - calculate Gravity...
float gravity = average_calc(gravities);
//STAGE 5b - print your answer
Serial.print("gravity = ");
Serial.print(gravity);
Serial.print(" ms^-2");
delay(10000); //wait for 10 seconds - LEAVE THIS FOR RELOAD TO WORK PROPERLY!
}
//Function finds gravity based on half period
float gravity_calc(unsigned long half_T) {
float gravity = sq(PI)*pendulength / sq(half_T) ;
return gravity;
}
//Function finds average of an array (length 9)
float average_calc(float gravities[]) {
float sum = 0;
for (int i = 0; i < 9; i++) {
sum = sum + gravities[i];
}
return sum / 9;
}
//Function checks progress of experiment
void progress_check(float gravities[]) {
// Print each element of the gravities array
for (int i = 0; i < 9; i++) {
Serial.print(gravities[i]);
Serial.print(", ");
}
Serial.println(); // Move to the next line after printing the array
}