Welcome, Guest. Please login or register.

Author Topic: Mr. Biehl learns C  (Read 7261 times)

Description:

0 Members and 1 Guest are viewing this topic.

Offline koaftder

  • Hero Member
  • *****
  • Join Date: Apr 2004
  • Posts: 2116
    • Show all replies
    • http://koft.net
Re: Mr. Biehl learns C
« on: April 19, 2005, 08:50:55 AM »
C is a lot of fun. Lately ive been doing some development with an 8052 microcontroller. I have a situation where i need to buffer data coming in various interrupts, and i need to get to that data in the order it was received, and with minimal delay. I've implimented a ring buffer, which is 16 bytes in length and resides in near memory for fast access.

One of the fun things about c is trying to put together the most efficient algorithms you can come up with. This is the most efficient way i could figure to impliment a ring buffer:
Code: [Select]

[font=Courier]
char buf[16];
int head ;
int tail ;

void put ( char data ) {
if ( ++head > 16 )
head = 0 ;
if ( head == tail ) {
if ( ++tail > 16 )
tail = 0 ;
}
buf[head] = data ;
}

char snatch ( void ) {
char c ;
if ( head == tail ) {
// this queue is empty
} else {
if ( ++tail > 16 )
tail = 0 ;
}
c = buf[tail] ;
return c ;
}[/font]