Playing with Arduino
A page to record my playing with Arduino
shiftOut()

# Abstract

The shiftOut() sends a byte of data bit by bit.

# Source Code

The shiftOut() is defined in hardware/arduino/avr/cores/arduino/wiring_shift.c as below.

 `````` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 `````` ``````void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val) { uint8_t i; for (i = 0; i < 8; i++) { if (bitOrder == LSBFIRST) { digitalWrite(dataPin, val & 1); val >>= 1; } else { digitalWrite(dataPin, (val & 128) != 0); val <<= 1; } digitalWrite(clockPin, HIGH); digitalWrite(clockPin, LOW); } }``````

The inputs are dataPin, clockPin, bitOrder and val, they all are uint8_t, returns nothing.

 ``````1 2 3 `````` ``````void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val) { uint8_t i;``````

It loops to send 8 bits of data.

 `````` 5 6 7 8 9 10 11 12 `````` `````` for (i = 0; i < 8; i++) { if (bitOrder == LSBFIRST) { digitalWrite(dataPin, val & 1); val >>= 1; } else { digitalWrite(dataPin, (val & 128) != 0); val <<= 1; }``````

When the bitOrder is LSBFIRST, this function sends data from LSB. It sends the 0th bit of val by calculating bitwise AND of val and 1. Then shifts right by 1 bit to make next bit to be the 0th bit of val.

When the bitOrder is MSBFIRST, this function sends data from MSB. It sends the 7th bit of val by calculating bitwise AND of val and 128(= 0B10000000). Then shifts left by 1 bit to make next bit to be the 7th bit of val.

It uses digitalWrite() to send data.

Finally it sends a pulse making clockPin HIGH then LOW.

 ``````14 15 16 17 `````` `````` digitalWrite(clockPin, HIGH); digitalWrite(clockPin, LOW); } }``````

# Version

Arduino AVR Boards 1.8.6

# Last Update

March 21, 2023 