I have a logical gate with 3 inputs: a, b and c and an output "y".
How can I simplify this code:
#define DI0 2
#define DI1 3
#define DI2 4
int a = 0; // input logic gate
int b = 0; // input logic gate
int c = 0; // input logic gate
int y = 0;
void setup(){
pinMode(DI0, INPUT_PULLUP);
pinMode(DI1, INPUT_PULLUP);
pinMode(DI2, INPUT_PULLUP);
}
void loop(){
a = digitalRead(DI0);
b = digitalRead(DI1);
c = digitalRead(DI2);
if ( a == HIGH && b == HIGH && c == HIGH ) {
y = 0;
}
if ( a == HIGH && b == HIGH && c == LOW ) {
y = 1;
}
if ( a == HIGH && b == LOW && c == HIGH ) {
y = 2;
}
if ( a == HIGH && b == LOW && c == LOW ) {
y = 3;
}
...
if ( a == LOW && b == LOW && c == LOW ) {
y = 7;
}
}
// change the states of a, b, c and run
boolean a = HIGH; // input logic gate
boolean b = LOW; // input logic gate
boolean c = LOW; // input logic gate
int y = 0;
void setup()
{
Serial.begin(115200);
bitWrite(y, 0, !a);
bitWrite(y, 1, !b);
bitWrite(y, 2, !c);
Serial.print(" the value of y = ");
Serial.println(y);
}
void loop()
{
}
If this is not what you want, please present a full truth table.
Sometimes I'm confused what "simplify the code" means. Do you mean:
Rewrite the code to use fewer lines,
or:
Write the code so the compiler generates "better" code,
or:
Make the code easier to read?
The first goal doesn't always promote the third goal, and usually the compiler does a pretty good job on 2 regardless of the exact nature of the other two. Because so much time in code development is spent testing and debugging, I'd lean towards #3, not #1.
ok ok! It was just an example of the logic of the entrance.
In fact, according to counting circuits: (binary) 101 = (hex) 5;
A logic gate may be different.
Let's resume. Modified Code:
...
if ( a == 0 && b == 0 && c == 0 ) {
y = 0;
}
if ( a == 0 && b == 0 && c == 1 ) {
y = 1;
}
if ( a == 0 && b == 1 && c == 0 ) {
y = 2;
}
if ( a == 0 && b == 1 && c == 1 ) {
y = 3;
}
...
if ( a == 1 && b == 1 && c == 1 ) {
y = 7;
}
}
The first goal doesn't always promote the third goal, and usually the compiler does a pretty good job on 2 regardless of the exact nature of the other two. Because so much time in code development is spent testing and debugging, I'd lean towards #3, not #1.
Indeed, option 3 is ok, but I wanted to simplify the code.
Then I'd use John's last solution. Of course, come back a month later and you'll probably spend a little time remembering what it means and, as John carefully points out, that solution may not be portable.