Skip to content

Commit

Permalink
Added averaging to sensor for more accurate results
Browse files Browse the repository at this point in the history
  • Loading branch information
PAOK-2001 committed May 17, 2022
1 parent 53566de commit 7438221
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 12 deletions.
27 changes: 18 additions & 9 deletions CleanIt-SC/Headers/proximity.h
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
#ifndef PROXIMITY_H
#define PROXIMITY_H
#include <MKL25Z4.h>
#include <cstdio>
#include<math.h>
#include "delays.h"

void adc_init(void);
void proximity_init(void);
int proximity_read(int sensorValue);
int proximity_read_average(int sensorValue, int meassurments);

//adc_init()
// Initialized clock for ADC0 and configures necessary register.
Expand All @@ -20,21 +22,28 @@ void adc_init(void){
void proximity_init(void){
adc_init();
// Initialize clock to PORTB
SIM->SCGC4 |= 0x400;
SIM->SCGC5 |= 0x400;
// Set PORT B0 & PORT B1 as analogue input
PORTB->PCR[0] = 0;
PORTB->PCR[1] = 1;

}
//proximity_read()
// @param integer corresponding to ADC channel. Should be 8 or 9.
// @param sensorChannel: int corresponding to ADC channel. Should be 8 or 9.
// @param meassurments: measurments to average
// @returns int value corresponding to the sensor value
int proximity_read(int sensorChannel){
int readValue;
ADC0->SC1[0] = sensorChannel;
while(!(ADC0->SC1[0] & 0x80)) { } /* wait for COCO */
readValue = ADC0->R[0];
return readValue;
int proximity_read_average(int sensorChannel, int meassurments){
int rawValue,sum;
int valueCm;
sum = 0;
for (int i = 0; i < meassurments; i++){
ADC0->SC1[0] = sensorChannel;
while(!(ADC0->SC1[0] & 0x80)) { } /* wait for COCO */
sum = sum + ADC0->R[0];
delayMs(15);
}
rawValue = sum/meassurments;
return rawValue;
}

#endif
7 changes: 4 additions & 3 deletions CleanIt-SC/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@
// main() runs in its own thread in the OS
int main(){
printf("Program Begin\n");
tpm_init();
proximity_init();
int leftSensor, rightSensor;
while (true) {
//leftSensor = proximity_read(8);
printf("Loop\n");
//printf("%d\n", leftSensor);
leftSensor = proximity_read_average(8,20);
printf("%d\n", leftSensor);
tpm_delayMs(1000);

}
}
Expand Down

0 comments on commit 7438221

Please sign in to comment.