Sending PORTB via serial port

Hi everybody,

I'm trying to build a system that receives inputs from multiple foot switches (min 2, max 8 ) which sends its signal via USB.
This is easy by means of digitalRead and Serial.write, anyway if I have multiple pedals, because the digitalRead on each input pin of the foot switches are serailly read, there could be delays among them.

Therefore, because I want that these foot switches will work in parallel, I would like to use the arduino ports and send their state via USB... But I'm not succeding in this, the serial monitor is not showing any signal at all!

Here the code:

void setup()
{
  Serial.begin(9600);
  DDRB = B11111111; // set PORTB (digital 13~8) to outputs
  /*I've also tried by setting it at B00000000;*/
  
}

void loop()
{
  // Read data from serial communication
  if (Serial.available() > 0)
  {
    Serial.write(PINB);//trying if this works
    Serial.flush();
    Serial.write(PORTB);//trying if this works
    Serial.flush();
  }
}

Thanks in advance!

Michele

Try sending it as ASCII instead

 Serial.print((int)PINB);//trying if this works

Perfect AWOL, now it works.

I also had to remove
if (Serial.available() > 0)

because it was keeping the arduino waiting for an input that I was not planning to send :grin:

now the code reads as follows:

void setup()
{
  Serial.begin(9600);
  DDRB = B00000000; // set PORTB (digital 13~8) to outputs
  
}

void loop()
{
    Serial.write((int)PINB);
    Serial.flush();    
}

It is pointless to call Serial.flush() after every write. It is pointless to cast the byte PINB to an int to pass the data to a function that expects a byte.

Thanks a lot Paul_S,
you're right, I've tried to remove serial.flush(); and it works fine.
Do you have further suggestions to optimize the code?

You've got a single statement loop function - how much optimisation do you need?

 DDRB = B00000000; // set PORTB (digital 13~8) to outputs

Fix the comment. You are setting them to inputs. Makes sense since you are reading PINB--the input register variable.