I have been working on a code that would be essentially a car parking system to further create glasses out of this. I wanted to have an ultrasonic sensor get constant readings of the distance from the closest object, and then depending on the distance have the vibration motor vibrate as much. However, I realized I needed an interrupt as if the distance changed too suddenly from big dist to small dist the motor would not react tot he changes and this would be inaccurate. So I put in an interrupt which when the motor is on allows the sensor to work and give some reading, which to be honest barely works (not properly as it gets in readings only with the normal val reading not separately) and they also needed an interrupt to detect the 20% and skip to the start of the loop sequence. However, i realized that this would work as interrupts simply don't work like that. Please help me, i don't know what to do now
const int echoPin = 8;
int val = 0;
int val2 = 0;
const int motor1 = A0;
float duration = 0;
int Capval = 0; // captured value
boolean toggle1 = 0;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin (9600);
pinMode(motor1, OUTPUT);
Timer1.initialize(10000);
Timer1.attachInterrupt (RestartM);
cli(); //disable interupts
//TCCR1A = 0;
//TCCR1B = 0;
//TCNT1 = 0;
//OCR1A = 1000;
// TCCR1A |= (1 << WGM12 );
// TCCR1B |= (1 << CS12) | (1 << CS10);
// TIMSK1 |= (1 << OCIE1A);
sei(); // allow interupts
//set timer1 interrupt at 1Hz
TCCR1A = 0;// set entire TCCR1A register to 0
TCCR1B = 0;// same for TCCR1B
TCNT1 = 0;//initialize counter value to 0
// set compare match register for 1hz increments
OCR1A = 5208;// = (16*10^6) / (1*1024) - 1 (must be <65536)
// turn on CTC mode
TCCR1B |= (1 << WGM12);
// Set CS10 and CS12 bits for 1024 prescaler
TCCR1B |= (1 << CS12) | (1 << CS10);
// enable timer compare interrupt
TIMSK1 |= (1 << OCIE1A);
}
ISR(TIMER1_COMPA_vect) {
if (toggle1 && MotorStatus == "ON") {
digitalWrite(trigPin, LOW);
digitalWrite(trigPin, HIGH);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
val2 = (duration / 2) / 29.1;
toggle1 = 0;
}
else {
toggle1 = 1;
}
}
void loop() {
Serial.print (Capval);
Serial.print(" ");
Serial.print(val2);
Serial.print(" ");
Capval = 0;
val2 = 0;
MotorStatus = "OFF";
Serial.print(" ");
digitalWrite(trigPin, LOW);
delay(50);
digitalWrite(trigPin, HIGH);
delay(100);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
val = (duration / 2) / 29.1;
if (val <= 35) {
MotorStatus = "ON";
digitalWrite(motor1, HIGH);
}
else if (val > 35 && val < 250) {
Capval = val;
MotorStatus = "ON";
digitalWrite(motor1, HIGH);
delay(300);
digitalWrite(motor1, LOW);
delay(val * 2.5);
}
else if (val >= 250) {
MotorStatus = "OFF";
digitalWrite(motor1, LOW);
}
}
void RestartM () {
if (MotorStatus == "ON" && val2 / Capval < 0.8 && val2 / Capval > 1.2) {
//was supposed to skip to start of loop here
}
if (MotorStatus == "OFF") {
return;
}
}