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. In many cases, bit banging is made possible because more recent hardware operates much more quickly than hardware did when standard communications protocols were created.
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 (active low)
output_low(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_high(SD_CS);
}
Considerations
The question whether to deploy bit banging or not is a trade-off between load, performance and reliability on the one hand, and the availability of a hardware alternative on the other. The software emulation process consumes more processing power than does supporting dedicated hardware. The microcontroller spends much of its time sending or receiving samples to and from the pins, 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. The implementation in software can be a solution when specific hardware support is not available or requires a more expensive microcontroller.
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