Ibrahim Dogan - Advanced PIC Microcontroller Projects in C

Здесь есть возможность читать онлайн «Ibrahim Dogan - Advanced PIC Microcontroller Projects in C» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: Burlington, Год выпуска: 2008, ISBN: 2008, Издательство: Elsevier Ltd, Жанр: Программирование, Компьютерное железо, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Advanced PIC Microcontroller Projects in C: краткое содержание, описание и аннотация

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

• The only project book on the PIC 18 series using the C programming language
• Features 20 complete, tried and test projects
• Includes a CD-ROM of all the programs, hex listings, diagrams, and data sheets

Advanced PIC Microcontroller Projects in C — читать онлайн бесплатно полную книгу (весь текст) целиком

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

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

Интервал:

Закладка:

Сделать

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

TEMPERATURE LOGGER PROJECT

============================

In this project a SD card is connected to PORTC as follows:

CS RC2

CLK RC3

DO RC4

DI RC5

In addition, a MAX232 type RS232 voltage level converter chip

is connected to serial ports RC6 and RC7. Also, a LM35DZ type

analog temperature sensor is connected to analog input AN0 of

the microcontroller.

The program is menu based. The user is given options of either

to send the saved temperature data to the PC, or to read and

save new data on the SD card, or to read temperature data and

append to the existing file. Temperature is read at every 10

seconds.

The temperature is stored in a file called TEMPERTR.TXT

Author: Dogan Ibrahim

Date: August 2007

File: SD4.C

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

char filename[] = "TEMPERTRTXT";

unsigned short character;

unsigned long file_size,i,rec_size;

unsigned char ch1,ch2,flag,ret_status,choice;

unsigned char temperature[10],txt[12];

//

// This function sends carriage-return and line-feed to USART

//

void Newline() {

Usart_Write(0x0D); // Send carriage-return

Usart_Write(0x0A); // Send line-feed

}

//

// This function sends a space character to USART

//

void Space() {

Usart_Write(0x20);

}

//

// This function sends a text to serial port

//

void Text_To_Usart(unsigned char *m) {

unsigned char i;

i = 0;

while(m[i] != 0) { // Send TEXT to serial port

Usart_Write(m[i]);

i++;

}

}

//

// This function reads the temperature from analog input AN0

//

void Get_Temperature() {

unsigned long Vin, Vdec,Vfrac;

unsigned char op[12];

unsigned char i,j;

Vin = Adc_Read(0); // Read from channel 0 (AN0)

Vin = 488*Vin; // Scale up the result

Vin = Vin /10; // Convert to temperature in C

Vdec = Vin / 100; // Decimal part

Vfrac = Vin % 100; // Fractional part

LongToStr(Vdec,op); // Convert Vdec to string in op

//

// Remove leading blanks

//

j=0;

for(i=0;i<=11;i++) {

if(op[i] != ' ') // If a blank

{

temperature[j]=op[i];

j++;

}

}

temperature[j] = '.'; // Add “.”

ch1 = Vfrac / 10; // fractional part

ch2 = Vfrac % 10;

j++;

temperature[j] = 48+ch1; // Add fractional part

j++;

temperature[j] = 48+ch2;

j++;

temperature[j] = 0x0D; // Add carriage-return

j++;

temperature[j] = 0x0A; // Add line-feed

j++;

temperature[j]='\0';

}

//

// Start of MAIN program

//

void main() {

rec_size = 0;

//

// Configure A/D converter

//

TRISA = 0xFF;

ADCON1 = 0x80;

// Use AN0, Vref = +5V

//

// Configure the serial port

//

Usart_Init(2400);

//

// Initialize the SPI bus

//

Spi_Init_Advanced(MASTER_OSC_DIV16, DATA_SAMPLE_MIDDLE,

CLK_IDLE_LOW, LOW_2_HIGH);

//

// Initialize the SD card bus

//

while(Mmc_Init(&PORTC,2));

//

// Initialize the FAT file system

//

while(Mmc_Fat_Init(&PORTC,2));

//

// Display the MENU and get user choice

//

Newline();

Text_To_Usart("TEMPERATURE DATA LOGGER");

Newline();

Newline();

Text_To_Usart("1. Send temperature data to the PC");

Newline();

Text_To_Usart("2. Save temperature data in a new file");

Newline();

Text_To_Usart("3. Append temperature data to an existing file");

Newline();

Newline();

Text_To_Usart("Choice ? ");

//

// Read a character from the PC keyboard

//

flag = 0;

do {

if (Usart_Data_Ready()) // If data received

{

choice = Usart_Read(); // Read the received data

Usart_Write(choice); // Echo received data

flag = 1;

}

} while (!flag);

Newline();

Newline();

//

// Now process user choice

//

switch(choice) {

case '1':

ret_status = Mmc_Fat_Assign(&filename,1);

if (!ret_status) {

Text_To_Usart("File does not exist..No saved data...");

Newline();

Text_To_Usart("Restart the program and save data to the file...");

Newline();

for(;;);

} else {

//

// Read the data and send to UART

//

Text_To_Usart("Sending saved data to the PC...");

Newline();

Mmc_Fat_Reset(&file_size);

for(i=0; i

Mmc_Fat_Read(&character);

Usart_Write(character);

}

Newline();

text_To_Usart("End of data...");

Newline();

for(;;);

}

case '2':

//

// Start the A/D converter, get temperature readings every

// 10 seconds, and then save in a NEW file

//

Text_To_Usart("Saving data in a NEW file...");

Newline();

Mmc_Fat_Assign(&filename, 0x80); // Assign the file

Mmc_Fat_Rewrite(); // Clear

Mmc_Fat_Write("TEMPERATURE DATA - SAVED EVERY 10 SECONDS\r\n", 43);

//

// Read the temperature from A/D converter, format and save

//

for(;;) {

Mmc_Fat_Append();

Get_Temperature();

Mmc_Fat_Write(temperature,9);

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

Интервал:

Закладка:

Сделать

Похожие книги на «Advanced PIC Microcontroller Projects in C»

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


Отзывы о книге «Advanced PIC Microcontroller Projects in C»

Обсуждение, отзывы о книге «Advanced PIC Microcontroller Projects in C» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x