Bit banging
Bit banging is a technique for serial communications using software instead of dedicated hardware. Software directly sets and samples the state of pins on the microcontroller, and is responsible for all parameters of the signal: timing, levels, synchronization, etc. In contrast to bit banging, dedicated hardware (such as a modem, UART, or shift register) handles these parameters and provides a (buffered) data interface in other systems, so software is not required to perform signal demodulation. Bit banging can be implemented at very low cost, and is used in, for example, embedded systems.[1]
Although it is often considered to be something of a hack, bit banging does allow the same device to use different protocols with minimal or no hardware changes required.
C code example
Sending a byte on an SPI bus.
// transmit byte serially, MSB first
void send_8bit_serial_data(unsigned char data)
{
int i;
// select device
output_high(SD_CS);
// send bits 7..0
for (i = 0; i < 8; i++)
{
// consider leftmost bit
// set line high if bit is 1, low if bit is 0
if (data & 0x80)
output_high(SD_DI);
else
output_low(SD_DI);
// pulse clock to indicate that bit value should be read
output_low(SD_CLK);
output_high(SD_CLK);
// shift byte left so next bit will be leftmost
data <<= 1;
}
// deselect device
output_low(SD_CS);
}
Problems
There are some problems with bit banging. The software emulation process consumes more processing power than does supporting dedicated hardware. The microcontroller spends much of its time reading or sending samples to and from the pin, at the expense of other tasks. The signal produced usually has more jitter or glitches, especially if the processor is also executing other tasks while communicating. However, if the bit-banging software is interrupt-driven by the signal, this may be of minor importance, especially if control signals such as RTS, CTS, or DCD are available.
See also
References
- ↑ Michael Predko (2000). Programming and customizing PICmicro microcontrollers (2nd ed.). McGraw-Hill Professional. pp. 10–12. ISBN 978-0-07-136172-9.
External links
- Asynchronous serial (RS-232)
- I²C bus
- SPI bus