My code works perfectly, but I just want some insight on some problems that you guys might find. It lags a little when I run it.
int total;//total
int readings;// Analog read A1
int irnow;// the ir distance now
int average;// average of the ir readings
int newaverage;//the new average (see below)
int potValue;//potometer value
bool pauseSelected = false;
const int pot = A3;//potonometer
const int button = 8;//the button I'm pressing
const int NOIRRTA = 9;//NumberOfIRReadingsToAverage
const int vibrator = 2;
void setup() {
Serial.begin(9600);
pinMode(vibrator, OUTPUT);// led
pinMode(pot, INPUT);// input the potonometer
pinMode(button, INPUT_PULLUP);// activate the resistor in the aurdino and set the pin 8 as input
}
void loop() {
checkPauseButton();// check if the button is not pressed
if (pauseSelected == false) {
mainirprogram();// do the main program
}
}
void mainirprogram() {
irnow = 0;
total = 0;
while ( irnow < NOIRRTA)
{
readings = analogRead(A1);
total = total + readings;
irnow = irnow + 1;
}
average = total / NOIRRTA;
newaverage = map(average, 0, 1023, 150, 20);
potValue = analogRead(pot);
int mappedpot = map(potValue, 0, 1023, 0, 90);//the void to here is averaging it
Serial.println(newaverage);
if (newaverage < 140 - mappedpot) //if the new mapped average is below 390 - the value of the mapped //pot
{
digitalWrite(vibrator, HIGH);//turn vibrator on
}
else {
digitalWrite(vibrator, LOW);//else turn the vibrator low
}
}
// the if statements to here are checking if there is something in front of the infra-red. It is controlling the on-off of pin 2, my vibrator, aka beeper.
void checkPauseButton() {
const unsigned long DebounceInterval = 10; //milliseconds - ignore button state flips faster than this
static unsigned long lastButtonPress;
static int lastButtonState = HIGH;// this is just if the button was pressed, pin 8 I believe, the last pin state
int buttonState = digitalRead(button);
if (lastButtonState != buttonState)
{
digitalWrite(vibrator, LOW);//set the vibrator to low
//the button has changed since we last looked at it
lastButtonState = buttonState;
if (millis() - lastButtonPress > DebounceInterval)
{
//it last changed a long time ago, so this is a new event
lastButtonPress = millis(); //record the time that it changed
if (buttonState == LOW)// if button isn't pressed, pin 8
{
pauseSelected = !pauseSelected; //flip the pause state
}
}
}
}
Thanks!
squidsirymchenry