Hello to everybody,
I have settled the PWM on the pin 10 of my Arduino Mega to 1 kHz using Timer 2. After certain time, when a condition is reached (counter==1000), I want to output low signal (0V) from that pin. The problem is that my PIN will not go down even if i state digitalWrite(10, LOW);
That's my simple code:
const byte PULSES = 10; // Timer 2 "A" output: OC2A --> 1 kHz
const byte home_switch=9; // Pin 9 connected to Home Switch (Photointerrupter)
#define encoderPinA 2
#define encoderPinB 3
volatile int counter =0;
unsigned long time;
int incomingByte = 0; // for incoming serial data
void setup() {
pinMode (PULSES, OUTPUT);
pinMode(home_switch, INPUT_PULLUP);
pinMode(encoderPinA, INPUT);
pinMode(encoderPinB, INPUT);
attachInterrupt(digitalPinToInterrupt(encoderPinA), isr,RISING);
Serial.begin(9600);
delay(5); //
// set up Timer 2
int myEraserPulses = 7; // this is 111 in binary and is used as an eraser
TCCR2B &= ~myEraserPulses; // this operation (AND plus NOT), set the three bits in TCCR2B to 0
TCCR2A = _BV(COM2A0) | _BV(WGM21) | _BV(WGM20); // fast PWM
TCCR2B = _BV(WGM22) | _BV(CS21) | _BV(CS22); // 16MHz/256=62.5kHz
OCR2A = 30; // 62.5kHz/1kHz=62.5 (50% duty--> 30)
} // end of setup
void loop() {
if(counter==1000)
digitalWrite(10, LOW); //output 0 V so the motor will stop
else
digitalWrite(10, HIGH); // continue to output PWM at 1kHz
if (Serial.available() >= 0) { // read the incoming byte:
incomingByte = Serial.read();
Serial.print(counter);
Serial.print("\t");
Serial.print("Time: ");
time = millis();
Serial.println(time); //prints time since program started
if (incomingByte=='0') { //pressing 0 into the serial monitor to stop the program
while(1) { }
}
}
}
//Interrupts
void isr(){
int channel_A = digitalRead(encoderPinA);
int channel_B = digitalRead(encoderPinB);
if(channel_A == channel_B){
counter++;
}
else{
counter--;
}
}
Thanks for your help.