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++», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

The implementation of main is shown below. This code simply creates the two tasks and starts the operating system's scheduler. At such a high level the code should speak for itself. In fact, we've already discussed a similar code listing in the previous chapter.

#include "adeos.h"

void flashRed(void);

void helloWorld(void);

/*

* Create the two tasks.

*/

Task taskA(flashRed, 150, 512);

Task taskB(helloWorld, 200, 512);

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

*

* Function: main()

*

* Description: This function is responsible for starting the ADEOS

* scheduler only.

*

* Notes:

*

* Returns: This function will never return!

*

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

void main(void) {

os.start();

// This point will never be reached.

} /* main() */

9.2 Flashing the LED

As I said earlier, one of two things this application does is blink the red LED. This is done by the code shown below. Here the function flashRed is executed as a task. however, ignoring that and the new function name, this is almost exactly the same Blinking LED function we studied in Chapter 7. The only differences at this level are the new frequency (10 Hz) and LED color (red).

#include "led.h"

#include "timer.h"

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

*

* Function: flashRed()

*

* Description: Blink the red LED ten times a second.

*

* Notes: This outer loop is hardware-independent. However, it

* calls the hardware-dependent function toggleLed().

*

* Returns: This routine contains an infinite loop.

*

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

void flashRed(void) {

Timer timer;

timer.start(50, Periodic); // Start a periodic 50ms timer.

while (1) {

toggleLed(LED_RED); // Toggle the red LED.

timer.waitfor(); // Wait for the timer to expire.

}

} /* flashRed() */

The most significant changes to the Blinking LED program are not visible in this code. These are changes made to the toggleLed function and the Timer class to make them compatible with a multitasking environment. The toggleLed function is what I am now calling the LED driver. Once you start thinking about it this way, it might make sense to consider rewriting the driver as a C++ class and add new methods to set and clear an LED explicitly. However, it is sufficient to leave our implementation as it was in Chapter 7 and simply use a mutex to protect the P2LTCH register from simultaneous access by more than one task. [23] There is a race condition within the earlier toggleLed functions. To see it, look back at the code and imagine that two tasks are sharing the LEDs and that the first task has just called that function to toggle the red LED. Inside toggleLed, the state of both LEDs is read and stored in a processor register when, all of the sudden, the first task is preempted by the second. Now the second task causes the state of both LEDs to be read once more and stored in another processor register, modified to change the state of the green LED, and the result written out to the P2LTCH register. When the interrupted task is restarted, it already has a copy of the LED state, but this copy is no longer accurate! After making its change to the red LED and writing the new state out to the P2LTCH register, the second task's change will be undone. Adding a mutex eliminates this potential.

Here is the modified code:

#include "i8018xEB.h"

#include "adeos.h"

static Mutex gLedMutex;

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

*

* Function: toggleLed()

*

* Description: Toggle the state of one or both LEDs.

*

* Notes: This version is ready for multitasking.

*

* Returns: None defined.

*

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

void toggleLed(unsigned char ledMask) {

gLedMutex.take();

// Read P2LTCH, modify its value, and write the result.

//

gProcessor.pPCB->ioPort[1].latch ^= ledMask;

gLedMutex.release();

} /* toggleLed() */

A similar change must be made to the timer driver from Chapter 7 before it can be used in a multitasking environment. However, in this case there is no race condition. [24] Recall that the timer hardware is initialized only once — during the first constructor invocation — and thereafter, the timer-specific registers are only read and written by one function: the interrupt service routine. Rather, we need to use a mutex to eliminate the polling in the waitfor method. By associating a mutex with each software timer, we can put any task that is waiting for a timer to sleep and, thereby, free up the processor for the execution of lower-priority ready tasks. When the awaited timer expires, the sleeping task will be reawakened by the operating system.

Toward this end, a pointer to a mutex object, called pMutex , will be added to the class definition:

class Timer {

public:

Timer();

~Timer();

int start(unsigned int nMilliseconds, TimerType = OneShot);

int waitfor();

void cancel();

TimerState state;

TimerType type;

unsigned int length;

Mutex * pMutex;

unsigned int count;

Timer * pNext;

private:

static void interrupt Interrupt();

};

This pointer is initialized each time a software timer is created by the constructor. And, thereafter, whenever a timer object is started, its mutex is taken as follows:

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

*

* Method: start()

*

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

* underlying hardware timer.

*

* Notes: This version is ready for multitasking.

*

* 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);

}

//

// Take the mutex. It will be released when the timer expires.

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

Интервал:

Закладка:

Сделать

Похожие книги на «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