priorità tra isr su Arduino Mega

salve a tutti,

sto cercando di "mergiare" due codici che usano interrupt, il primo si occupa di controllare due encoder e l'altro di inviare stringhe ppm..

quello che vorrei è mandare in ppm i due valori degli encoder, ma mi chiedo:

il ppm è, se ho capito bene, una serie di valori con una pausa di una determinata lunghezza che determina fine del treno precedente ed inizio di quello successivo.

credo che il ppm sia gestito da un interrupt tipo timer, cosi da garantire il treno in orario, mentre gli encoder con interrupt esterni.

ho letto molte cose negli ultimi giorni e comincio ad essere confuso

quello che mi chiedo è:

come faccio a dire al mega di dare priorità al timer interrupt rispetto agli interrupt legati ai pin?

oppure potrei sganciare i pin degli interrupt quando sono all'interno della isr che gestisce il ppm?

mumble mumble

encoder

float pulsesX, XA_SIG=0, XB_SIG=1, pulsesY, YA_SIG=0, YB_SIG=1;

void setup(){
  attachInterrupt(0, XA_RISE, RISING); // Pin 2
  attachInterrupt(1, XB_RISE, RISING); // Pin 3
  attachInterrupt(4, YA_RISE, RISING); // Pin 19
  attachInterrupt(5, YB_RISE, RISING); // Pin 18
  Serial.begin(115200);
  delay(100);
  Serial.println("Connected"); 
}//setup


void loop(){
 Serial.print("x");
 Serial.print(pulsesX);
 Serial.print("y");
 Serial.print(pulsesY);
 Serial.println("end");
 delay(20);
}

//X-Axis

void XA_RISE(){
 detachInterrupt(0);
 //delay(1);
 XA_SIG=1;
 
 if(XB_SIG==0){
 pulsesX++;//moving forward
 }
 if(XB_SIG==1){
 pulsesX--;//moving reverse
}
 attachInterrupt(0, XA_FALL, FALLING);
}

void XA_FALL(){
  detachInterrupt(0);
  //delay(1);
 XA_SIG=0;
 
 if(XB_SIG==1){
 pulsesX++;//moving forward
 }
 if(XB_SIG==0){
 pulsesX--;//moving reverse
}
 attachInterrupt(0, XA_RISE, RISING);  
}

void XB_RISE(){
 detachInterrupt(1);
 //delay(1);
 XB_SIG=1;
 
 if(XA_SIG==1){
 pulsesX++;//moving forward
 }
 if(XA_SIG==0){
 pulsesX--;//moving reverse
}
 attachInterrupt(1, XB_FALL, FALLING);
}

void XB_FALL(){
 detachInterrupt(1);
 //delay(1);
 XB_SIG=0;
 
 if(XA_SIG==0){
 pulsesX++;//moving forwar
 }
 if(XA_SIG==1){
 pulsesX--;//moving reverse
}
 attachInterrupt(1, XB_RISE, RISING);
}

//Y-Axis

void YA_RISE(){
 detachInterrupt(4);
 //delay(1);
 YA_SIG=1;
 
 if(YB_SIG==0){
 pulsesY++;//moving forward
 }
 if(YB_SIG==1){
 pulsesY--;//moving reverse
}

 attachInterrupt(4, YA_FALL, FALLING);
}

void YA_FALL(){
  detachInterrupt(4);
  //delay(1);
 YA_SIG=0;
 
 if(YB_SIG==1){
 pulsesY++;//moving forward
 }
 if(YB_SIG==0){
 pulsesY--;//moving reverse
}
 attachInterrupt(4, YA_RISE, RISING);  
}

void YB_RISE(){
 detachInterrupt(5);
 //delay(1);
 YB_SIG=1;
 
 if(YA_SIG==1){
 pulsesY++;//moving forward
 }
 if(YA_SIG==0){
 pulsesY--;//moving reverse
}
 attachInterrupt(5, YB_FALL, FALLING);
}

void YB_FALL(){
 detachInterrupt(5);
 //delay(1);
 YB_SIG=0;
 
 if(YA_SIG==0){
 pulsesY++;//moving forward
 }
 if(YA_SIG==1){
 pulsesY--;//moving reverse
}
 attachInterrupt(5, YB_RISE, RISING);
}

ppm

// Data variables
unsigned int ppm[16]; // the array of values for the timer1 interrupt timings
unsigned int potVal; // value read from potemtiometer
int curPpm = 0; // the position in the array of timings
byte curPpmMax; // the actual number of timer steps

char pulsePin = 7; // the digital pin for sending pulses to the transmitter
char debugPin = 13; // something to watch to check things are working
char potPin = 2; // the analog pin for the potentiometer

byte loopCount = 0; // a crude substitute for delay()
int analogIn; // for reading potentiometer position


boolean testing = true;

void setup() {

  if (testing) {
		Serial.begin(9600);
		Serial.println("Starting TrainRadioPot");
	}

// set the pin directions
  pinMode(pulsePin, OUTPUT);
//  pinMode(debugPin, OUTPUT); 
  
// set the timing values
  ppm[0] = 1475; //3775; // long pulse - see notes above
  ppm[1] = 75; // short dividing pulse
  ppm[2] = 305; // loco1 ch1
  ppm[3] = 75; // short
  ppm[4] = 305; // loco2 ch2
  ppm[5] = 75; // short
  ppm[6] = 305; // loco3 ch3
  ppm[7] = 75; // short
  ppm[8] = 305; // loco4 ch4
  ppm[9] = 75; // short
  ppm[10] = 305; // loco5 ch5
  ppm[11] = 75; // short
  ppm[12] = 305; // loco6 ch6
  ppm[13] = 75; // short
  ppm[14] = 305; // loco7 ch7
  ppm[15] = 75; // short

	curPpmMax = 16; // the number of timer values
  curPpm = 0; // the starting position in the array of timings
  
  // setup and start timer interrupts
  // ppm is achieved by sending different delays to the timer interrupt
  noInterrupts();
		TCCR1A = 0;     // set entire TCCR1A register to 0
		TCCR1B = 0;     // same for TCCR1B
		// set compare match register to desired timer count:
		OCR1A = 1000; // It works by causing an interrupt when TCNT2 counts up to this number
		              // This number will be set from the ppm array when the program is running
		digitalWrite(pulsePin,0); // start with pin low
		// turn on CTC mode: Clear Timer on Compare
		bitSet(TCCR1B, WGM12);
		// Set CS10 and CS11 bits for 64 prescaler: 10, 12 = 1024
		bitSet(TCCR1B, CS10);
		bitSet(TCCR1B, CS11);
		bitClear(TCCR1B, CS12);
		// enable timer compare A interrupt:
		bitSet(TIMSK1, OCIE1A);
	interrupts();

}

void loop() {

	if (loopCount == 1) {
		analogIn = analogRead(potPin);
		// the reading must be converted from the range 0 - 1023 to the range 250 - 500
		//   which means dividing by 4 and adding 180 to give 305 at the centre
		potVal = (analogIn >> 2) + 180;
		if (potVal > 302 && potVal < 308) {
			potVal = 305; // to create an off space without jitter
		} 
		ppm[2] = potVal;
	}

//	loopCount = 0; // for testing - so analog read is ignored
	loopCount = loopCount + 1; // it will roll over to zero automatically
	              // the purpose of loopCount is so that the pot isn't read every loop
}
  

// interrupt routine that is triggered when the timer counts up to the preset value
ISR(TIMER1_COMPA_vect) {
	noInterrupts();
		digitalWrite(pulsePin, !digitalRead(pulsePin)); // change the state of the pin
		OCR1A = ppm[curPpm]; // set the value for the next time interval
		curPpm = ((curPpm + 1) % curPpmMax); // move the index on
		                                     // the modulus operator makes the index roll over to the start
	interrupts();
}

grazie tante

Sulla Mega e sulla uno non hai priorità d'interrupt, nel senso che quando un interrupt viene scatenato e la relativa isr richiamata gli interrupt vengono disabilitati, quindi se sei dentro la isr la MCU non intercetta altri eventi d'interrupt, da qui la necessità (solitamente) di mantenere le ISR più veloci nell'esecuzione possibile. A dirla tutta c'è un flag che intercetta un secondo interrupt mentre il primo è ancora in esecuzione, all'uscita della ISR se è stato intercettato allora parte anche l'ISR dell'interrupt relativo, ma se ne arriva due o più mentre un'ISR è in esecuzione questi vengono irremediabilmente persi.
Tra l'altro nell'ISR, e non so quanto serva, la prima cosa che viene fatta è quella di disabilitare gli interrupt e riattivarli alla fine. Quindi se stai gestendo i ppm l'encoder non lo senti proprio

Nelle piccole MCU AVR non esiste la possibilità di assegnare una priorità agli interrupt, ma la priorità è data dalla loro posiziione nella tabella vettoriale degli interrupt (in allegato) ...

Quando un interrupt scatta viene chiamata la relativa ISR ed immediatamente disabilitati altri interrupt siano a quando non si esce dalla ISR. Il fatto che siano disabilitati non significa che vengano persi, ma vengono accodati ed eseguiti in base alla priorità dettata dalla suddetta tabella.

La cosa più corretta è, come già detto, fare la ISR la più veloce possibile e cercare di demandare la parte elaborativa fuori della ISR. Ad esempio, una ISR protrebbe semplicemente alzare una "flag" ed il codice poi, se trova tale "flag" alzata, come prima cosa la resetta e poi fa quello che deve fare così che, se nel fattempo arriva di nuovo lo stesso interrupt, non viene perso, ma la "flag" di nuovo alzata e, contemporaneamente, se arriva un differente interrupt, può comunque essere intercettato.

Guglielmo

gpb01:
Il fatto che siano disabilitati non significa che vengano persi, ma vengono accodati ed eseguiti in base alla priorità dettata dalla suddetta tabella.

Questa precisazione spazzia via tutte le certezze che avevo sugli interrupt degli AVR :slight_smile:
Non viene accodato un solo interrupt mentre uno è in esecuzione? o meglio ne vengono accodati N per ciascun interrupt, uno per ciascun interrupt o uno in assoluto? Da quel che hai riportato sembra ce ne accodi N indipendentemente dal tipo d'interrupt

Per ogni interrupt esiste una "interrupt flag" ... viene semplicemente attivata quella e quindi la MCU sa che c'è un interrupt pendente ... basta leggere con attenzione il paragrafo 11.7 del datasheet

11.7. Reset and Interrupt Handling
The AVR provides several different interrupt sources. These interrupts and the separate Reset Vector each have a separate program vector in the program memory space. All interrupts are assigned individual enable bits which must be written logic one together with the Global Interrupt Enable bit in the Status Register in order to enable the interrupt. Depending on the Program Counter value, interrupts may be automatically disabled when Boot Lock bits BLB02 or BLB12 are programmed. This feature improves software security.
The lowest addresses in the program memory space are by default defined as the Reset and Interrupt Vectors. They have determined priority levels: The lower the address the higher is the priority level. RESET has the highest priority, and next is INT0 – the External Interrupt Request 0. The Interrupt Vectors can be moved to the start of the Boot Flash section by setting the IVSEL bit in the MCU Control Register (MCUCR). The Reset Vector can also be moved to the start of the Boot Flash section by programming the BOOTRST Fuse.
When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are disabled. The user software can write logic one to the I-bit to enable nested interrupts. All enabled interrupts can then interrupt the current interrupt routine. The I-bit is automatically set when a Return from Interrupt instruction – RETI – is executed.
There are basically two types of interrupts:
The first type is triggered by an event that sets the Interrupt Flag. For these interrupts, the Program Counter is vectored to the actual Interrupt Vector in order to execute the interrupt handling routine, and hardware clears the corresponding Interrupt Flag. Interrupt Flags can also be cleared by writing a logic one to the flag bit position(s) to be cleared. If an interrupt condition occurs while the corresponding interrupt enable bit is cleared, the Interrupt Flag will be set and remembered until the interrupt is enabled, or the flag is cleared by software. Similarly, if one or more interrupt conditions occur while the Global Interrupt Enable bit is cleared, the corresponding Interrupt Flag(s) will be set and remembered until the Global Interrupt Enable bit is set, and will then be executed by order of priority.
The second type of interrupts will trigger as long as the interrupt condition is present. These interrupts do not necessarily have Interrupt Flags. If the interrupt condition disappears before the interrupt is enabled, the interrupt will not be triggered. When the AVR exits from an interrupt, it will always return to the main program and execute one more instruction before any pending interrupt is served.
The Status Register is not automatically stored when entering an interrupt routine, nor restored when returning from an interrupt routine. This must be handled by software.
When using the CLI instruction to disable interrupts, the interrupts will be immediately disabled. No interrupt will be executed after the CLI instruction, even if it occurs simultaneously with the CLI instruction.

Guglielmo