Streaming Serial Data to Single Bits

Hello all, I apologize for the easy question.

I’m interfacing 4 switches and, hopefully if things go well, a sensor into Max/MSP, but lets start with the easy stuff.

I have a handle on getting multiple inputs into Arduino, but they come out in a stream, rather than singular bits, which seems like a dumb waste of CPU. I simply want a switch to send a signal of either ON or OFF, 1 or 0.

Thank you for any advice!

Here is the sketch.

int INPIN1 = 2; 
int INPIN2 = 3;
int INPIN3 = 4;
int INPIN4 = 5;

int val1 = 0;
int val2 = 0;
int val3 = 0;
int val4 = 0;

void setup() {
  Serial.begin(9600);

}

void loop() {

  val1 = digitalRead(INPIN1);
  val2 = digitalRead(INPIN2); 
  val3 = digitalRead(INPIN3); 
  val4 = digitalRead(INPIN4); 

  Serial.println(val1);
  delay (10);
  Serial.println(val2);
  delay (10);
  Serial.println(val3);
  delay (10);
  Serial.println(val4);
  delay (10);
}

Moderator edit: [code][/code] tags added. Also reformatted code. (Nick Gammon)

What you need to get a handle on is the difference between level and edge detection.

The digitalRead() function returns the "level" of the input - i.e., the HIGH or LOW current status.

What you are really interested in is only those times when the input changes from HIGH to LOW or LOW to HIGH. This is called "edge" detection - looking for the edges of the waveform that comes in through the input.

The easiest way is to just remember what the value was the last time you did a digitalRead() and compare that to the current value. If they differ, then you have an edge, and you can do something. All the rest of the time you do nothing, just looping around.

There is no "waste" of CPU, as the CPU is always running regardless, there is only inefficiency of code - how many clock cycles it takes to do the job you want to do.

brcm:
they come out in a stream, rather than singular bits

Do you mean how they're printed on the serial monitor? You can change the Serial.println to Serial.write to send raw bits. If you mean something else, please clarify (unless majenko nailed it)

The delay calls don't achieve a heap, except to make it look more "stream like". Maybe one big delay at the end if you don't want to spam the serial monitor.

First, get smart and turn on the internal pullups so the next question isn't "why do they change be themselves?"

Then, get smarter and read all 4 using direct port manipulation and just send 1 byte out.
Then, make it smarter & only send a byte when 1 of them is changed from the prior read.
Then, get really smart and use interrupts, and don't even read them unless 1 gets pulled low to create an interrupt.
Then, ...

Thank you all! I got it working just right using

  if(state1 != val1 ) {
    state1 = val1;   
    Serial.print("1 "); Serial.println(val1);}

Hopefully I'm set from here on out, but probably not since this is all new to me.

Thanks again!