Nil RTOS update - Fast and Tiny!

Q: what will happen when the compare value drifts closer to 255/0 (OVF isr for millis) because of "OCR0A += 250;" ?

The timer counter, TCNT0, just increments and the overflow ISR doesn't change anything. So the compare ISR is not affected by the overflow ISR.

Adding 250 really just subtracts 6 counts or 24 microseconds until the next compare match. As long as interrupt are not disabled for around a millisecond this will be reliable.

So when compare value will be 0, the ovf and compare isr fire simultaneously, I think. Will be both isrs processed properly then?

So when compare value will be 0, the ovf and compare isr fire simultaneously, I think. Will be both isrs processed properly then?

It will work correctly but there will be a little jitter in the time. Interrupt priority on AVR is by vector location.

The interrupts have priority in accordance with their Interrupt Vector position. The lower the Interrupt Vector address, the higher the priority.

The TIMER0 COMPA interrupt is higher priority than TIMER0 OVF so the Nil systick should be processed first if both occur on the same CPU cycle.

I have several tasks, two of them handle I2C. First reads ads1110 ADC (per. every 100ms) and the second one reads an external RTC (for example each second). Running both tasks accessing single I2C bus does not work well - it comes to data corruption.
What is the proper handling of such situation under NilRtos?

You could share the I2C bus by using a semaphore. Each thread that uses the I2C bus has this form.

// Declare and initialize a semaphore for limiting access to a region.
SEMAPHORE_DECL(i2cSem, 1);

// Time between acceses. 
const systime_t PERIOD_ONE_TICKS = 123;  // set value for your case!
//------------------------------------------------------------------------------
// Declare the thread function.
NIL_THREAD(thdFcn, arg) {
  // Time for next read.
  systime_t wakeTime = nilTimeNow();
 
  while (true) {
    wakeTime += PERIOD_ONE_TICKS;

    // Sleep until time for next bus access.
    nilThdSleepUntil(wakeTime);
    
    // Wait for access to I2C bus.
    nilSemWait(&i2cSem);

    // Access I2C bus here.
    
    // Release I2C bus.
    nilSemSignal(&i2cSem);
  }
}

Another option is to access one of the devices with software I2C.

See: DigitalIO20130221.zip - Fast digital I/O, software I2C, and software SPI http://code.google.com/p/rtoslibs/downloads/list.

ok, so something like handshaking:

// Wait for access to I2C bus.
    nilSemWait(&i2cSem);                     <<  waits on signal I2C is free (resource semaphore 1 -> 0 )
    // Access I2C bus here.    
    // Release I2C bus.
    nilSemSignal(&i2cSem);                   >>  signals I2C is free (resource semaphore 0 -> 1 )

I'll try..
thx..it seems it works.. now I know why we need counting semaphores :slight_smile:

It might be nice if Nil had a Mutex which is intended for mutual exclusion. Here is an excellent little article ChibiOS free embedded RTOS - This topic does not exist yet.

Could be the setsyncProvider() with setSyncInterval() used in setup() with Nirtos? Or better, a task shall be used for syncing (instead of the setSyncInterval())?

    setSyncProvider(RTC.get);   // the function to get the time from the actual RTC
.. 
     setSyncInterval(300);         // set the number of seconds between re-sync of time
     nilSysBegin();

What are setSyncProvider() and setSyncInterval()? They are not in the posted version of NilRTOS.

It comes from Time.h
PS: setSyncProvider() calls RTC in regular intervals in order to sync "local time" (based on millis(). So it seems it must be guarded by a mutex.

You just need to define a protected function to return the time. All access to I2C must be protected by the same semaphore.

time_t safeGetTime() {
  time_t t;
  nilSemWait(&i2cSem);   
  t = RTC.get();
  nilSemSignal(&i2cSem);
  return t;
}

  ...

  setSyncProvider(safeGetTime);   // the function to get the time from the actual RTC

I did it with a periodic task. Yours is more resource friendly, of course :slight_smile:

	while (TRUE) {

		wakeTime += SYSTIME_SYNC_PERIOD_TICKS;

		// Sleep until time for next data point
		nilThdSleepUntil(wakeTime);

		// Read RTC..
		nilSemWait(&i2cfree);
		new_time = rtc.get_tm();
		nilSemSignal(&i2cfree);
		// .. and sync system Time and Date
		setTime(new_time);
		now();  // this makes the sync
	}
}

Q: can I work with semaphores before I start the NilRtos? Like:

 ..
	// SYNC the RTC and systime at boot
	setSyncProvider(safeGetTime);   // the function to get the time from RTC
	if(timeStatus()!= timeSet) 
		Serial.println("Unable to sync with the RTC");
	else
		Serial.println("RTC has set the system time");  
	setSyncInterval(300); // set the number of seconds between re-sync of time
	sys_t_start = now(); // keep the boot start time
..
nilSysBegin();

While running above I get a proper time into "sys_t_start" var - it means the setSyncProvider() has called the safeGetTime() already.. So it had worked with semaphores, before the NilRtos actually started..

You will get away with calling safeGetTime before starting Nil since there will be no wait on the semaphore. nilSemWait will decrement the count to zero and return.

It won't work if you need to wait.

I've installed SdFat's demos (Bench and SdInfo) into my Nil experimental setup. The issue is they use SdFat and Sd2Card respectively. So to put them together work with

SdFat sd;
Sd2Card card;

only, I was not able to merge the stuff such it uses only one class for the card. And it works :astonished: (very surprised though) under Nil even under "heavy" load (several periodic tasks run in bg) ;).

PITO> sdinfo
SDINFO

SdFat version: 20130710

init time: 15 ms

Card type: SDHC

Manufacturer ID: 0X3
OEM ID: SD
Product: SU04G
Version: 8.0
Serial number: 35763829101
Manufacturing date: 11/2012

cardSize: 3965.19 MB (MB = 1,000,000 bytes)
flashEraseSize: 128 blocks
eraseSingleBlock: true

SD Partition Table
part,boot,type,start,length
1,0X0,0XB,8192,7733248
2,0X0,0X0,0,0
3,0X0,0X0,0,0
4,0X0,0X0,0,0

Volume is FAT32
blocksPerCluster: 64
clusterCount: 120704
freeClusters: 112067
freeSpace: 3672.21 MB (MB = 1,000,000 bytes)
fatStartBlock: 14496
fatCount: 2
blocksPerFat: 944
rootDirStart: 2
dataStartBlock: 16384

PITO> sdbench
SDBENCH
Free RAM: -1203
Type is FAT32
File size 5MB
Buffer size 1024 bytes
Starting write test.  Please wait up to a minute
Write 140.21 KB/sec
Maximum latency: 442936 usec, Minimum Latency: 3252 usec, Avg Latency: 7294 usec

Starting read test.  Please wait up to a minute
Read 400.25 KB/sec
Maximum latency: 5784 usec, Minimum Latency: 2196 usec, Avg Latency: 2551 usec

Done

PITO> stack
STACK
Stack Sizes: 197 85 85 101 101 85 117 85 117 197 85 197 165 197 197 309 309 10107
Unused Stack: 165 55 55 47 49 55 87 55 87 58 55 167 41 71 167 192 50 9995
PITO>

BTW the FreeRam() does not work under Nil well.

This is how I did the error states handling inside a thread. The thread starts based on a signal from CLI. Is there any better option how to handle the error states within a Nilrtos thread?

// Declare the thread function
NIL_THREAD(SdBench, arg) {
	while (TRUE) {
		// Wait for signal from CLI
		nilSemWait(&sdbench);

		// initialize the SD card at SPI_FULL_SPEED for best performance.
		// try SPI_HALF_SPEED if bus errors occur.
		if (!sd.begin(chipSelect, SPI_FULL_SPEED)) {
			error("\nsd.init failed");
			goto thrdend1;
		}
..
		// open or create file - truncate existing file.
		if (!file.open("BENCH.DAT", O_CREAT | O_TRUNC | O_RDWR)) {
			error("open failed");
			goto thrdend1;
		}
..
		for (uint32_t i = 0; i < n; i++) {
			uint32_t m = micros();
			if (file.write(buf, sizeof(buf)) != sizeof(buf)) {
				error("write failed");
				goto thrdend1;
			}
..
		for (uint32_t i = 0; i < n; i++) {
			buf[BUF_SIZE-1] = 0;
			uint32_t m = micros();
			if (file.read(buf, sizeof(buf)) != sizeof(buf)) {
				error("read failed");
				goto thrdend1;
			}
..
			if (buf[BUF_SIZE-1] != '\n') {
				error("data check");
				goto thrdend1;
			}
..
thrdend1:		file.close();
	}     // This is the While ()
}   // This is the NIL_THREAD()

PS: Plz do not discuss goto here.. :slight_smile:

The issue is they use SdFat and Sd2Card

SdInfo was meant to be a standalone diagnostic so I didn't use the SdFat class which wraps Sd2Card, SdVolume, and the root file.

I wanted to first initialize the SD card and get info that didn't depend on the card format. I then initialize SdVolume and check the format.

You probably have two copies of SdVolume. Surprised it works.

STACK
Stack Sizes: 197 85 85 101 101 85 117 85 117 197 85 197 165 197 197 309 309 10107
Unused Stack: 165 55 55 47 49 55 87 55 87 58 55 167 41 71 167 192 50 9995

Looks like you are going beyond the design thread count for Nil. I removed this when I made the thread count dynamic.

#if NIL_CFG_NUM_THREADS > 12
#error "Nil is not recommended for thread-intensive applications, consider" \
       "ChibiOS/RT instead"
#endif

Nil uses very simple algorithms for scheduling that involve scanning tables. ChibiOS uses more conventional linked lists to order objects for more efficiency when there are many objects. This also allows dynamic priorities and priority inheritance for a mutex.

Is there any better option how to handle the error states within a Nilrtos thread?

Alarms, events, and logging are major components of large embedded systems. Usually there is an API for threads to communicate with this module using something like mail boxes. Error messages are logged and displayed for operators. Operators can acknowledge errors and reply to threads.

Here are two links that illustrate the scale of this subsystem.

An old link to FANL which had the Tevatron http://www-ad.fnal.gov/controls/micro_p/errlog.html#ch-2

A newer link for an LHC experiment at CERN http://iopscience.iop.org/1742-6596/396/1/012038/pdf/1742-6596_396_1_012038.pdf

BTW the FreeRam() does not work under Nil well.

That's why Stack Size and Unused Stack exist in Nil.

Here is the NIL_CFG_NUM_THREADS at the default level (2).. Surprised how well the stuff work..

Q2: when I print out the cnt_t of my semaphores (semaphores initiated to 0 and not signaled), I get -1 as the result

..
SEMAPHORE_DECL(sdlog, 0);
..
// Declare the thread function
NIL_THREAD(SdLog, arg) {
while (TRUE) {
nilSemWait(&sdlog);
..

..
Serial.print("sdlog = ");
Serial.println(nilSemGetCounter(&sdlog));
..
sdlog = -1

Is that ok?

Thanks.

   nilSemWait(&sdlog);

Makes the count -1.

A counting semaphore is a synchronization object that can have an arbitrarily large number of states. The internal state is defined by a signed integer variable, the counter. The counter value (N) has a precise meaning:

Negative, there are exactly -N threads queued on the semaphore.
Zero, no waiting threads, a wait operation would put in queue the invoking thread.
Positive, no waiting threads, a wait operation would not put in queue the invoking thread.

Two operations are defined for counting semaphores:

Wait (chSemWait() in ChibiOS/RT). This operation decreases the semaphore counter, if the result is negative then the invoking thread is queued.

Signal (chSemSignal() in ChibiOS/RT). This operation increases the semaphore counter, if the result is non-negative then a waiting thread is removed from the queue and resumed.

There are some updates related to Nilrtos at chibios.org - do you plan an update too?