Using pyserial to input values to a shift register?

Hello! I’m working on a project of consisting of 5 shift registers with 8 outputs each and 40 led’s I wish to turn on and off. The goal is to input specific led numbers through pyserial and have the shift registers cycle through turning on the corresponding lights.

My code so far looks like:

int dataPin = 11;
int clockPin = 12;
int latchPin = 13;

void setup() {
pinMode(dataPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(latchPin, OUTPUT);
Serial.begin(9600);
Serial.print (“Ready\n”);
}

void loop() {
while(Serial.available()>0)
{
// Led number is the assignment of led’s to turn on.
int led_number = {1,3,5,7,8};
// X is the the array of 40 led’s and is 1 if it is on or 0 if it is off.
int x[40];

// Initializes latch pin as low before data is input
digitalWrite(latchPin, LOW);

// ‘i’ cycles through each led
for (int i = 1; i<= 40; i++)
{
digitalWrite(clockPin,LOW);
digitalWrite(dataPin, LOW);

// ‘j’ cycles through led number array
for (int j=0; j<= sizeof(led_number)/sizeof(int) - 1; j++)
{
if (i==led_number[j])
{
// Data shifts from low to high if it is the led number assigned.
digitalWrite(dataPin,HIGH);
x[i-1]=1;
break;
}
else
{
digitalWrite(dataPin,LOW);
x[i-1]=0;
}
}
digitalWrite(clockPin,HIGH);
}

for (int v=0;v<40;v++)
{
Serial.print(x[v]);
}

Serial.print(’\n’);
// Latch shifts from low to high when the cycle is complete.
digitalWrite(latchPin,HIGH);
}
}

The issues are that this should only run once when I put an input but it continues to loop. Also, I do not know how to incorporate a pyserial input as opposed to the current input in the arduino code (being the ‘led_number’ array).

Any help would be awesome! Thanks!

while(Serial.available()>0)

You never actually read anything from the serial buffer so once it is not zero it remains not zero.

Read the forum rules about how to post code in the sticky post at the start of this section.

Grumpy_Mike: while(Serial.available()>0)

You never actually read anything from the serial buffer so once it is not zero it remains not zero.

This is what I figured for that part, Thank you. But I am still having issues seeing as the input of led numbers could be anywhere from 1 to 40. It is difficult to initialize the array. I tried running a while loop of available serial data but it is a local variable and does not return to outside the loop.

Generally you initialise an array with a for loop.

You can put the value of Serial.avaliable into a variable if you need it. But unless you empty the buffer with a read you will be trapped. Still no code tags in that first post.