Bit shift not functioning as expected

I am playing a bit with a tm1638 module to get a grip on the C programming (I am an absolute newbe). What I am trying to do is to create a “knight rider” scheme with the 8 led’s on the tm1638 module by using the bit shift operators >> and <<.

My code is as follows:

<pre>
#include <TM1638.h>

TM1638 module(52, 51, 50);    // define a module on data pin 3, clock pin 2 and strobe pin 4
word startByte = B10000000;
long previousMillis = 0;        // will store last time LED was updated
long interval = 3000;           // interval at which to blink (milliseconds)
  
void setup() {
  module.setDisplayToHexNumber(0x1234ABCD, 0xF0);  // display a hexadecimal number and set the left 4 dots
  module.setLEDs(startByte); // set led's according startByte
  Serial.begin(9600);      // open the serial port at 9600 bps:   
}
    
void loop() {
setLed();
}

void setLed()
{

  unsigned long currentMillis = millis(); // sets the clock data (command millis)
  int a = 1; // for switching direction right and left
  
  if(currentMillis - previousMillis > interval)  
  {
    previousMillis = currentMillis;  // save the last time you blinked the LED

    if (a == 1 ) startByte >>= 1; // move 1 bit to the right
    if (a == 0 ) startByte <<= 1; // move 1 bit to the left

    if (startByte == B00000001) a = 0; // reverse movement
    if (startByte == B10000000) a = 1;
    
    Serial.print(a);
    Serial.print("\t");    // prints a tab
    Serial.println(startByte, BIN);

  
  module.setLEDs(startByte); // set led's according startByte
    }
}
</pre>

When I check the serial monitor I get the following (a is left, startByte right)
1 1000000
1 100000
1 10000
1 1000
1 100
1 10
0 1
1 0
1 0
1 0
1 0
1 0

Where I would expect:
1 10000000
1 01000000
1 00100000

But the 0’s on the left are not inserted nor does the direction change work when a changes.

In praxis this means that the led runs from one side to the other with a 3 sec interval but then instead of reversing no more leds light up.

Anybody any idea on what I am doing wrong?

Thanks

Anybody any idea on what I am doing wrong?

Please repost your code as it is not readable by some humans.. ;)

Done, as said I'm a newbie... :roll_eyes:

mantas: But the 0's on the left are not inserted

Serial.print suppresses leading zeros when you ask it to print a number.

mantas: nor does the direction change work when a changes.

Although you correctly switch 'a' between 0 and 1 in setLed(), you re-initialise it to 1 every time you re-enter setLed. Try moving the line "int a = 1;" outside setLed(). Alternatively, leave it where it is and change it to "static int a = 1;". Either way, the initialization to 1 will only be done once.

Thanks very much, "static int a" solved the issue and good to know the S.M. doesn't return the 1st zero's