avr-gcc-list
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [avr-gcc-list] Serial Communication


From: Neil Johnson
Subject: Re: [avr-gcc-list] Serial Communication
Date: Thu, 29 Jan 2004 10:25:40 +0000 (GMT)

Hi,

> > #define USART_TX_BUFFER_MASK ( USART_TX_BUFFER_SIZE - 1 )

> The mask is used to maintain a ring buffer.

**CAUTION**

The masking trick works if the size of the buffer is a power of 2,
e.g. 2, 4, 8, 16, 32, 64, 128, 256, 512, etc

That way you can use bitwise AND to do the wraparound, e.g.

        index = (index + 1) & USART_TX_BUFFER_MASK;

For any other buffer size you need to use the more expensive modulo
operator "%":

        index = (index + 1) % USART_TX_BUFFER_MASK;

So its not really what I would call a mask as such, and possibly better to
use ( USART_TX_BUFFER_SIZE - 1 ) as its then more obvious in the source
code exactly what's going on ("mask" implies a bitwise operation).

Discussion: one *could* stick with the BUFFER_SIZE value and hope the
compiler optimizes unsigned-modulo-with-(2^n) into bitwise AND-with-(2^n - 1).

Neil

--
Neil Johnson :: Computer Laboratory :: University of Cambridge ::
http://www.njohnson.co.uk          http://www.cl.cam.ac.uk/~nej22
----  IEE Cambridge Branch: http://www.iee-cambridge.org.uk  ----


reply via email to

[Prev in Thread] Current Thread [Next in Thread]