Taltech_embedded/common/reflectance.c

110 lines
2.6 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "reflectance.h"
#include "delay.h"
#include "inc/msp432p401r.h"
void ReflectanceInit(void) {
P5->SEL0 &= ~0x08;
P5->SEL1 &= ~0x08; // configure P5.3 as GPIO
P5->DIR |= 0x08; // make P5.3 output
P5->OUT &= ~0x08; // set output low
P9->SEL0 &= ~0x04;
P9->SEL1 &= ~0x04; // configure P9.2 as GPIO
P9->DIR |= 0x04; // make P9.2 output
P9->OUT &= ~0x04; // set output low
P7->SEL0 &= ~0x255;
P7->SEL1 &= ~0x255; // configure P7.0-7 as GPIO
P7->DIR &= ~0x255; // make them input
// P7->REN |= 0x255; //? enable pull resistors
}
// 0 -> while, 1 -> black
uint8_t ReflectanceRead(uint32_t time) {
uint8_t input;
// 1) Set P5.3 and P9.2 high (turn on IR LED)
P5->OUT |= 0x08;
P9->OUT |= 0x04;
// 2) Make P7.7 P7.0 outputs, and set them high (charging 8 capacitors)
P7->DIR |= 0x255;
P7->OUT |= 0x255;
// 3) Wait 10 us, Delay1us(10);
Delay1us(10);
// 4) Make P7.7 P7.0 input
P7->DIR &= ~0x255;
// 5) Wait time us, Delay1us(time);
Delay1us(time);
// 6) Read P7.7 P7.0 inputs (converts voltages into binary)
input = P7->IN;
// 7) Set P5.3 and P9.2 low (turn off IR LED, saving power)
P5->OUT &= ~0x08;
P9->OUT &= ~0x04;
//P7->DIR &= ~0x255;
//P7->OUT &= ~0x255;
// 8) Return 8-bit binary measured in step 6
return input;
}
int32_t ReflectancePosition(uint8_t sensor_data) {
// Data falls into four categories:
// 1) <all 0s> (off the line or on white surface)
// 2) <some 0s, some 1s>, e.g., 00000111 (off to the left)
// 3) <some 0s, some 1s, some 0s>, e.g., 00110000 (over the line)
// 4) < some 1s, some 0s>, e.g., 11110000 (off to the right)
int32_t W[] = {334, 238, 142, 48, -48, -142, -238, -334};
// if (!sensor_data) return 0; // off the line or on white surface
int32_t i, up, down, b;
for (up = down = i = 0; i < 8; ++i) {
b = (sensor_data & (1 << i)) != 0;
up += b * W[i];
down += b;
}
return up / down;
}
void ReflectanceStart(void) {
// turn on 4 even IR LEDs
// turn on 4 odd IR LEDs
P5->OUT |= 0x08;
P9->OUT |= 0x04;
// make P7.7-P7.0 out
P7->DIR |= 0x255;
// prime for measurement
P7->OUT |= 0x255;
// wait 10 us
Delay1us(10);
// make P7.7-P7.0 in
P7->DIR &= ~0x255;
}
uint8_t ReflectanceEnd(void) {
uint8_t input;
// convert P7.0 input to digital
input = P7->IN;
// turn off 4 even IR LEDs
// turn off 4 odd IR LEDs
P5->OUT &= ~0x08;
P9->OUT &= ~0x04;
return input;
}