//260414

/* 
* ISR INTEGRATION
* pro: we do use the standard atatchInterrupt from Arduino , easy etc
*
* ISR PINS TO USE

UNO(328P):  https://jensd.dk/doc/arduino/pins/uno.png

pin 2  (INT0) 
pin 3  (INT1)

MEGA(2560) https://jensd.dk/doc/arduino/pins/mega.png
 pin 21 INT0  NB: I2C SCL pin as well
 pin 20 INT1  NB: I2C SDA pin as well
 pin 19 INT2
 pin 18 INT3
 pin  2 INT4
 pin  3 INT5

 Atmega32u4 based micro
 intr 0,1,2,3,   intr is special - it you used it beware
Arduino micro(32u4 based)
pin 18 INT0
pin 19 INT1
pin 20 INT2
pin 21 INT3
pin  1 INT6

 NB NB NB 
 Only krnl calls allowd in isr: ki_signal and ki_send
 When using Arduino install of interrupts( attachInterrupt) you are not allowed to call krnls scheduler.

 So in worst case the task started by a interrupt krnl call (ki_signal, ki_send) will be running withn1 msec (at next krnl timer tick)

 SO NO K_CHG_STAK(); 	PUSHREGS(); 	POPREGS();	RETI();
}
* 
*/
 
#include <krnl.h>

// stak size
#define STK 150


char stkTask1[STK], stkTask2[STK];

#define TASKPRIO 10

struct k_t
  *pTask1,
  *pTask2,
  *isrSyncSem, *timedSem;


volatile int isrCount = 0, localCpy = 0;

void myISR() {
	isrCount++;
	ki_signal(isrSyncSem);
}

void task1() {
	 
	 int cn=0;

	k_set_sem_timer(timedSem, 500);
	while (1) {
		k_wait(timedSem, 0);
		Serial.print("isr counter ");
		Serial.print(cn++);
		Serial.print(" ");
		Serial.println(localCpy);
	}
}


void task2() {

	while (1) {
		k_wait(isrSyncSem, 0); // wait on kick from ISR
		// to ensure atomic access to isrCOunt you might disable interrupt

		DI(); // disable interrupt  - takes approx 62.5 nanosec
		localCpy = isrCount;
		EI();  // enable interrupt  - takes approx 62.5 nanosec
	}
}

void setup() {
	Serial.begin(115200);
	delay(500);

	Serial.println("\n\njust bef init part");


	k_init(2, 2, 0);  // 2 task, 2 semaphores, 0 messaegQueues */

	pTask1 = k_crt_task(task1, 15, stkTask1, STK);
	pTask2 = k_crt_task(task2, 15, stkTask2, STK);

	isrSyncSem = k_crt_sem(0, 10);  // 1: start value, 10: max value (clipping)
	timedSem = k_crt_sem(0, 10);    // 1: start value, 10: max value (clipping)

	pinMode(2, INPUT_PULLUP);  // for isr

	attachInterrupt(digitalPinToInterrupt(2), myISR, FALLING);  // install ISR

	Serial.println("justr bef start");

	k_start(); /* start krnl timer speed 1 milliseconds*/

	Serial.println("If you see this then krnl didnt start :-( ");
}

void loop() {}
