Let’s understand the logic gates,
Truth tables of all gates give us a clear idea of how gates work.
1.AND GATE ( 2-INPUT )
INPUT A | INPUT B | OUTPUT |
0 | 0 | 0 |
0 | 1 | 0 |
1 | 0 | 0 |
1 | 1 | 1 |
2.OR GATE (2-INPUT)
INPUT A | INPUT B | OUTPUT |
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 1 |
3.NOR GATE(2-INPUT)
INPUT A | INPUT B | OUTPUT |
0 | 0 | 1 |
0 | 1 | 0 |
1 | 0 | 0 |
1 | 1 | 0 |
4.NAND GATE(2-INPUT)
INPUT A | INPUT B | OUTPUT |
0 | 0 | 1 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
As the slide switch has three terminals,
uint8_t gate_leds[4] = { 2, 3, 4, 5 }; // Pins for the LEDs representing logic gates (OR, AND, NOR, NAND)
uint8_t switch_pins[2] = { 8, 9 }; // Pins for the switches (inputs A and B)
uint8_t input_a = 1, input_b = 1; // Variables to store the states of switches A and B
uint8_t ButtonState[2] = { HIGH, HIGH }; // Store the state of each button
void setup() {
// Configure gate LED pins as outputs
for (int i = 0; i < 4; i++) {
pinMode(gate_leds[i], OUTPUT);
}
// Configure switch pins as inputs
for (int i = 0; i < 2; i++) {
pinMode(switch_pins[i], INPUT_PULLUP);
}
}
void loop() {
input_a = !digitalRead(switch_pins[1]);
input_b = !digitalRead(switch_pins[0]);
//LEDs update only when inputs A or B change.
if ( input_a != ButtonState[1] || input_b != ButtonState[0]) {
// Perform logic gate operations and update the corresponding LEDs state
digitalWrite(gate_leds[0], input_a | input_b); // OR operation
digitalWrite(gate_leds[1], input_a & input_b); // AND operation
digitalWrite(gate_leds[2], !(input_a | input_b)); // NOR operation
digitalWrite(gate_leds[3], !(input_a & input_b)); // NAND operation
ButtonState[1] = input_a;
ButtonState[0] = input_b;
}
}