About

The following program demonstrates a sleep that uses timer.device to pause the program for 5 seconds. This is the preferred method to using a blocking sleep since it waits from an OS-level signal when the specified time has been elapsed.

Code

sleep5.c
/*************************************************************************/
/*    Copyright (C) 2015 Wizardry and Steamworks - License: GNU GPLv3    */
/*************************************************************************/
/*                                                                       */
/*  sleep5                                                               */
/*                                                                       */
/*  Sleeps for 5 seconds by using timer.device                           */
/*                                                                       */
/*  Compile using SASC: sc link sleep5.c                                 */
/*                                                                       */
/*************************************************************************/
 
#include <exec/types.h>
#include <exec/memory.h>
#include <devices/timer.h>
 
#include <clib/exec_protos.h>
#include <clib/alib_protos.h>
 
#include <stdio.h>
 
#define SLEEP_SECONDS 5
 
int main(void) {
    struct timerequest *TimerIO;
    struct MsgPort *TimerMP;
    struct Message *TimerMSG;
 
    /* Create port. */
    if (!(TimerMP = CreatePort(0, 0))) {
        printf("error: could not create port.\n");
        return 1;
    }
 
    /* Create IO port */
    if (!(TimerIO = (struct timerequest*)CreateExtIO(TimerMP, sizeof(struct timerequest)))) {
        printf("error: could not create timer IO port.\n");
        return 1;
    }
 
    /* Open timer device. */
    if (OpenDevice(TIMERNAME, UNIT_VBLANK, (struct IORequest*)TimerIO, 0L)) {
        printf("error: could not open device.\n");
        return 1;
    }
 
    /* Set command to TR_ADDREQUEST. */
    TimerIO->tr_node.io_Command = TR_ADDREQUEST;
    /* Set seconds to SLEEP_SECONDS. */
    TimerIO->tr_time.tv_secs = SLEEP_SECONDS;
 
    printf("sleeping for %d seconds.\n", SLEEP_SECONDS);
    SendIO((struct IORequest*)TimerIO);
    WaitPort(TimerMP);
    TimerMSG = GetMsg(TimerMP);
    if (TimerMSG == (struct Message*)TimerIO) {
        printf("%d seconds elapsed.\n", SLEEP_SECONDS);
    }
 
    /* Close device. */
    CloseDevice((struct IORequest*)TimerIO);
    /* Delete timer port. */ 
    DeleteExtIO((struct IORequest*)TimerIO);
    /* Delete port. */
    DeletePort(TimerMP);                     
 
    return 0;
}