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

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

Интервал:

Закладка:

Сделать

Let's take a look at the SerialPort constructor. This routine is responsible for initializing the three private data members and configuring the requested data channel within the SCC hardware:

#include "scc.h"

static SCC scc;

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

*

* Method: SerialPort()

*

* Description: Default constructor for the serial port class.

*

* Notes:

*

* Returns: None defined.

*

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

SerialPort::SerialPort(int port, unsigned long baudRate, unsigned int txQueueSize, unsigned int rxQueueSize) {

//

// Initialize the logical device.

//

switch (port) {

case PORTA:

channel = 0;

break;

case PORTB:

channel = 1;

break;

default:

channel = –1;

break;

}

//

// Create input and output FIFOs.

//

pTxQueue = new CircBuf(txQueueSize);

pRxQueue = new CircBuf(rxQueueSize);

//

// Initialize the hardware device.

//

scc.reset(channel);

scc.init(channel, baudRate, pTxQueue, pRxQueue);

} /* SerialPort() */

Once a SerialPort object has been created, the aforementioned methods for sending and receiving data can be used. For example, in the helloWorld function shown earlier, puts("Hello,World!") is the statement that sends the text string to serial port A (a.k.a. SCC channel 0). The data is sent over the serial channel at a rate of 19,200 bits per second, as selected by the baudRate parameter to the SerialPort constructor.

The send and receive methods rely on the circular buffers pointed to by pTxQueue and pRxQueue , respectively. pTxQueue is a transmit buffer that provides overflow memory in case the rate at which characters are sent by the application exceeds the baud rate of the channel. This usually happens in short spurts, so it is expected that the transmit buffer won't usually fill up all the way. Similarly, the receive buffer, pRxQueue , provides overflow memory for bytes that have been received at the serial port but not yet read by the application. By default, the above constructor creates each of these as 64-byte buffers. However, these sizes can be set to smaller or larger values, depending on the needs of your application, simply by overriding the default arguments to the constructor.

The implementations of the send methods putchar and puts are shown below. In putchar we start by checking if the transmit buffer is already full. If so, we return an error indication to the caller, so he will know that the character was not sent. Otherwise, we add the new character to the transmit buffer, ensure that the SCC transmit engine is running, and return success. The puts method makes a series of calls to putchar , one for each character in the string and then adds a newline character at the end.

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

*

* Method: putchar()

*

* Description: Write one character to the serial port.

*

* Notes:

*

* Returns: The transmitted character is returned on success.

* -1 is returned in the case of an error.

*

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

int SerialPort::putchar(int c) {

if (pTxQueue->isFull()) {

return (-1);

}

//

// Add the character to the transmit FIFO.

//

pTxQueue->add((char) c);

//

// Start the transmit engine (if it's stalled).

//

scc.txStart(channel);

return (c);

} /* putchar() */

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

*

* Method: puts()

*

* Description: Copies the null-terminated string s to the serial

* port and appends a newline character.

*

* Notes: In rare cases, this function may return success though

* the newline was not actually sent.

*

* Returns: The number of characters transmitted successfully.

* Otherwise, -1 is returned to indicate error.

*

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

int SerialPort::puts(const char * s) {

const char * p;

//

// Send each character of the string.

//

for (p = s; *p != '\0'; p++) {

if (putchar(*p) < 0) break;

}

//

// Add a newline character.

//

putchar('\n');

return ((p – s) + 1);

} /* puts() */

The receive method getchar is similar to putchar . It starts by checking if the receive buffer is empty. If so, an error code is returned. Otherwise, one byte of data is removed from the receive buffer and returned to the caller. The gets method calls getchar repeatedly until either a newline character is found or there is no more data available at the serial port. It then returns whatever string was found up to that point. The code for both of these methods follows:

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

*

* Method: getchar()

*

* Description: Read one character from the serial port.

*

* Notes:

*

* Returns: The next character found on this input stream.

* -1 is returned in the case of an error.

*

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

int SerialPort::getchar(void) {

int c;

if (pRxQueue->isEmpty()) {

return (-1); // There is no input data available.

}

int rxStalled = pRxQueue->isFull();

//

// Read the next byte out of the receive FIFO.

//

c = pRxQueue->remove();

//

// If the receive engine is stalled, restart it.

//

if (rxStalled) {

scc.rxStart(channel);

}

return (c);

} /* getchar() */

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

*

* Method: gets()

*

* Description: Collects a string of characters terminated by a new-

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

Интервал:

Закладка:

Сделать

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