Michael Barr - Programming Embedded Systems in C and C++

Здесь есть возможность читать онлайн «Michael Barr - Programming Embedded Systems in C and C++» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Год выпуска: 1999, ISBN: 1999, Издательство: O'Reilly, Жанр: Программирование, Компьютерное железо, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Programming Embedded Systems in C and C++: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Programming Embedded Systems in C and C++»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

This book introduces embedded systems to C and C++ programmers. Topics include testing memory devices, writing and erasing Flash memory, verifying nonvolatile memory contents, controlling on-chip peripherals, device driver design and implementation, optimizing embedded code for size and speed, and making the most of C++ without a performance penalty.

Programming Embedded Systems in C and C++ — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Programming Embedded Systems in C and C++», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Finally, there is a private method called Interrupt –our interrupt service routine. The Interrupt method is declared static because it is not allowed to manipulate the data members of the individual software timers. So, for example, the interrupt service routine is not allowed to modify the state of any timer. By using the keyword static , this restriction is automatically enforced for us by the C++ compiler.

The most important thing to learn from the class declaration is that, although all of the software timers are driven by the same hardware timer/counter unit, each has its own private data store. This allows the application programmer to create multiple simultaneous software timers and the device driver to manage them behind the scenes. Once you grasp that idea, you're ready to look at the implementation of the driver's initialization routine, API, and interrupt service routine.

The constructor for the Timer class is responsible for initializing both the software timer and the underlying hardware. With respect to the latter, it is responsible for configuring the timer/counter unit, inserting the address of the interrupt service routine into the interrupt vector table, and enabling timer interrupts. However, because this method is a constructor that may be called several times (once for each of the Timer objects declared), our implementation of the constructor must be smart enough to perform these hardware initializations only during the very first call to it. Otherwise, the timer/counter unit might be reset at an inopportune time or become out of sync with the device driver.

That is the reason for the static variable bInitialized in the following code. This variable is declared with an initial value of zero and set to one after the hardware initialization sequence has been performed. Subsequent calls to the Timer constructor will see that bInitialized is no longer zero and skip that part of the initialization sequence.

#include "i8018xEB.h"

#include "timer.h"

#define CYCLES_PER_TICK (25000/4) // Number of clock cycles per tick.

/**********************************************************************

*

* Method: Timer()

*

* Description: Constructor for the Timer class.

*

* Notes:

*

* Returns: None defined.

*

**********************************************************************/

Timer::Timer(void) {

static int bInitialized = 0;

//

// Initialize the new software timer.

//

state = Idle;

type = OneShot;

length = 0;

count = 0;

pNext = NULL;

//

// Initialize the timer hardware, if not previously done.

//

if (!bInitialized) {

//

// Install the interrupt handler and enable timer interrupts.

//

gProcessor.installHandler(TIMER2_INT, Timer::Interrupt);

gProcessor.pPCB->intControl.timerControl &= ~(TIMER_MASK | TIMER_PRIORITY);

//

// Initialize the hardware device (use Timer #2).

//

gProcessor.pPCB->timer[2].count = 0;

gProcessor.pPCB->timer[2].maxCountA = CYCLES_PER_TICK;

gProcessor.pPCB->timer[2].control = TIMER_ENABLE | TIMER_INTERRUPT | TIMER_PERIODIC;

//

// Mark the timer hardware initialized.

//

bInitialized = 1;

}

} /* Timer() */

The global object gProcessor is declared in a header file called i8018xEB.h . It represents the Intel 80188EB processor. The i8018xEB class is something that i wrote, and it includes methods to make interaction with the processor and its on-chip peripherals easier. One of these methods is called installHandler , and its job is to insert an interrupt service routine into the interrupt vector table. This class also includes a global data structure called PCB that can be overlaid upon the memory-mapped registers of the peripheral control block. [19] Astute readers might recall that in Chapter 5, I stated that the PCB was located in the I/O space of the 80188EB processor. However, because memory-mapped registers are more likely in a device driver situation, I've relocated the entire PCB to physical address 72000h, in the memory space. This new location will be assumed for the rest of the book. To see how this relocation was performed, take a look at the constructor for the i8018xEB class. The three registers associated with timer/counter unit 2 make up just one small part of this 256-byte structure. (For purely aesthetic reasons, I've implemented the PCB data structure as a set of nested structures. Hence, the control register of timer/counter unit 2 is accessible as pPCB->timer[2].control .)

The initialization of the timer/counter unit consists of resetting its count register to 0, loading the maxCountA register with the countdown length, and setting several bits within the control register. What we are doing above is starting a 1 ms periodic timer that generates an interrupt at the end of each cycle. (This periodic timer will act as the clock tick we need to create software timers of arbitrary lengths.) The value that is loaded into maxCountA can be determined mathematically because it represents the number of clock cycles input to the timer/counter unit in a 1 ms period. According to the 80188EB databook, this will be one fourth of the number of processor cycles in a 1 ms period. So, for a 25 MHz processor like the one we're using (that's 25,000,000 cycles per second, or, if you prefer, 25,000 cycles per millisecond), maxCountA should be set to 25,000/4 — as it is in the constant CYCLES_PER_TICK earlier.

Once the hardware has been initialized and the clock tick established, it is possible to start a software timer of any length, so long as that length can be expressed as an integral number of ticks. Because our clock tick is 1 ms long, the application programmer can create timers of any length from 1 to 65,535 ms (65.536 seconds). He would do this by calling the start method:

/**********************************************************************

*

* Method: start()

*

* Description: Start a software timer, based on the tick from the

* underlying hardware timer.

*

* Notes:

*

* Returns: 0 on success, -1 if the timer is already in use.

*

**********************************************************************/

int Timer::start(unsigned int nMilliseconds, TimerType timerType) {

if (state != Idle) {

return (-1);

}

//

// Initialize the software timer.

//

state = Active;

type = timerType;

length = nMilliseconds / MS_PER_TICK;

//

// Add this timer to the active timer list.

//

timerList.insert(this);

return (0);

} /* start() */

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Programming Embedded Systems in C and C++»

Представляем Вашему вниманию похожие книги на «Programming Embedded Systems in C and C++» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Programming Embedded Systems in C and C++»

Обсуждение, отзывы о книге «Programming Embedded Systems in C and C++» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x