How to shift binary into a shift register (serial in, parallel out) sequentially

The use of pow. pow does return a double (depending on the Arduino, that can be a float instead) and floating point numbers are not necessarily exact. Below code demonstrates

void setup()
{
  Serial.begin(115200);
  for (int i = 1; i < 16; i++)
  {
    Serial.print(i);
    Serial.print("\t");
    Serial.print(pow(2, i));
    Serial.print("\t");
    shift_SIPO(pow(2, i));
  }
}

void loop()
{
}

void shift_SIPO(int sequence)
{
  Serial.println(sequence);
}

Result:

1	2.00	2
2	4.00	3
3	8.00	7
4	16.00	15
5	32.00	31
6	64.00	63
7	128.00	127
8	256.00	255
9	512.00	511
10	1024.00	1023
11	2048.00	2047
12	4096.00	4095
13	8192.00	8192
14	16383.99	16383
15	32767.98	32767

The better approach is to use an unsigned variable, set it to 1 and shift that

void setup()
{
  Serial.begin(115200);
  uint16_t x = 1;
  for (int i = 1; i < 16; i++)
  {
    x <<= 1;
    Serial.print(i);
    Serial.print("\t");
    Serial.print(x);
    Serial.print("\t");
    shift_SIPO(x);
  }
}

void loop()
{
}

void shift_SIPO(int sequence)
{
  Serial.println(sequence);
}

Result:

1	2	2
2	4	4
3	8	8
4	16	16
5	32	32
6	64	64
7	128	128
8	256	256
9	512	512
10	1024	1024
11	2048	2048
12	4096	4096
13	8192	8192
14	16384	16384
15	32768	-32768

Note the negative number; reason is that you tell shift_SIPO that the number is an int, not an unsigned int. It should not affect what is written out.

1 Like