A program that would test two input gates (AND, OR, NAND, NOR, and XOR)

2.5k views Asked by At

I am trying to design an Arduino program that would meet these parameters. At first I thought that this would not be that hard, but I don't know of what sort of logic or a way to think about approaching this problem. Now I am a little stuck. Anyways, here is what I have so far. Any help and input is much appreciated. Thanks.

1

There are 1 answers

8
ikegami On

The basic logic is:

- For out in 3, 6, 8, 11,
  - is_and = is_or = is_xor = is_nand = is_nor = true.

  - For p in 0, -1,
    - Set pin out-2 to (p ? HIGH : LOW).
    - For q in 0, -1,
      - Set pin out-1 to (q ? HIGH : LOW).
      - Read pin out.
      - If the value read isn't equal (p & q ? HIGH : LOW),
        - is_and = false.
      - If the value read isn't equal (p | q ? HIGH : LOW),
        - is_or = false.
      - If the value read isn't equal (p ^ q ? HIGH : LOW),
        - is_xor = false.
      - If the value read isn't equal (p & q ? LOW : HIGH),
        - is_nand = false.
      - If the value read isn't equal (p | q ? LOW : HIGH),
        - is_nor = false.

  - If is_and,
    - Print "AND".
  - Else if is_or,
    - Print "OR".
  - Else if is_xor,
    - Print "XOR".
  - Else if is_nand,
    - Print "NAND".
  - Else if is_nor,
    - Print "NOR".
  - Else
    - Print "???".

int out_pins[4] = { 3, 6, 8, 11 };
const int num_out_pins = sizeof(out_pins) / sizeof(out_pins[0]);

void setup() {
   int i = num_out_pins;
   while (i--) {
      pinMode(out_pins[i],   OUTPUT);
      pinMode(out_pins[i-1], INPUT);
      pinMode(out_pins[i-2], INPUT);
   }
}

void test_gate(int out_pin) {
   boolean is_and  = true;
   boolean is_or   = true;
   boolean is_xor  = true;
   boolean is_nand = true;
   boolean is_nor  = true;

   for (int p=0; p>-2; --p) {
      digitalWrite(out_pin-2, (p ? HIGH : LOW))
      for (int q=0; p>-2; --p) {
         digitalWrite(out_pin-1, (q ? HIGH : LOW))
         // Is a delay needed here?
         int out = digitalRead(out_pin);
         if (out == (p & q ? HIGH : LOW)) is_nand = false; else is_and = false;
         if (out == (p | q ? HIGH : LOW)) is_nor  = false; else is_or  = false;
         if (out != (p ^ q ? HIGH : LOW)) is_xor  = false;
      }
   }

   if (is_and) {
      printf("%d is the output of an AND gate\n", out_pin);
   }
   else if (is_or) {
      printf("%d is the output of an OR gate\n", out_pin);
   }
   else if (is_xor) {
      printf("%d is the output of an XOR gate\n", out_pin);
   }
   else if (is_nand) {
      printf("%d is the output of a NAND gate\n", out_pin);
   }
   else if (is_nor) {
      printf("%d is the output of a NOR gate\n", out_pin);
   }
   else {
      printf("%d is the output of an unrecognized gate\n", out_pin);
   }
}

void test_chip() {
   for (int i=0; i<num_out_pins; ++i) {
      test_gate(i, out_pins[i]);
   }
}

void loop() {
   test_chip();
   delay(1000);
}