Hello there. I've started learning coding with Arduino because of my job and I've had a good start with it. Now I've encountered an frustrating problem with using interrupts and PWM signals.
So I'm using Arduino Nano (the most awesome cat in the world, may he rest in peace) and I've made a program which generates PWM signal and does some other stuff. The signal is 50kHz with around 5% duty cycle. Overall the code is working like a charm. I have my PWM signal and temperature control etc.
The problems started when I was supposed to improve and add features to my code. I was supposed to add a button and when pressed it would trigger interrupt service and switch state of a variable. With that variable the program decides what to do. PWM or continuous signal.
It seems that even tho I've added "RISING" or "FALLING" pin detect interrupt with
attachInterrupt(digitalPinToInterrupt(interruptVALINTAKYTKIN), VALINTAKYTKIN, FALLING);
the program keeps on triggering with both falling and rising edge. I've added some capacitor to the switch to prevent the bouncing and verified this with my oscilloscope.
Now when I comment out following lines from my code;
pinMode (PULSSI_PWM, OUTPUT);
pinMode (PUHALLIN_PWM, OUTPUT);
which are my PWM outputs it seems that the triggering on both falling and rising edge disappears. What could be causing this? Is the problem with PWM and them using timers? Could you guys help me out with this?
Here is the code overall;
#include <SPI.h>
#include <TimerOne.h>
#include "Adafruit_MAX31855.h"
#define MAXDO 6
#define MAXCS 4
#define MAXCLK 5const byte PULSSI_PWM = 3;
const byte PUHALLIN_PWM = 10;
const byte interruptVALINTAKYTKIN = 2;
const byte interruptONOFFKYTKIN = 12;
volatile byte ONOFFled = 11;
volatile byte VALINTAKYTKINled = 13;Adafruit_MAX31855 thermocouple(MAXCLK, MAXCS, MAXDO);
float d;
float c1 = 100;
float c2;
int e=10;
int f=20;
volatile int VALINTAKYTKINtila = 1;
bool ONOFFtila = 0;
int sykli = 0;void setup()
{
pinMode (PULSSI_PWM, OUTPUT);
pinMode (PUHALLIN_PWM, OUTPUT);
pinMode(interruptVALINTAKYTKIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(interruptVALINTAKYTKIN), VALINTAKYTKIN, FALLING);
Serial.begin(9600);TCCR2A = bit (WGM20) | bit (WGM21) | bit (COM2B1);
TCCR2B = bit (WGM22) | bit (CS21);OCR2A = 39;
TCCR1A = bit (WGM10) | bit (WGM11) | bit (COM1B1);
TCCR1B = bit (CS11) | bit (WGM12) | bit (WGM13);
OCR1A = 79;
d = 30;
}void VALINTAKYTKIN(){
VALINTAKYTKINtila = !VALINTAKYTKINtila;
EIFR = bit (INTF0); // clear flag for interrupt 0 (PIN D2)}
void PULSSI() {
OCR2B = 1; //duty cycle for 50kHz PWM
while(VALINTAKYTKINtila == 1){
IRRELEVANT CODE HERE
}void TEHO(){
double c = thermocouple.readCelsius();
sykli = 0;
while(VALINTAKYTKINtila == 0){
IRRELEVANT CODE HERE
}void loop(){
if(VALINTAKYTKINtila == 0){
TEHO();
delay(200);
}
else{
PULSSI();
delay(200);
}}
Please feel free to correct my mistakes I've possibly made and hope you can help me with this! Thanks!