0

我正在尝试设计一个满足这些参数的 Arduino 程序。起初我认为这不会那么难,但我不知道解决这个问题的逻辑或方法是什么。现在我有点卡住了。无论如何,是我到目前为止所拥有的。非常感谢任何帮助和输入。谢谢。

4

1 回答 1

1

基本逻辑是:

- 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);
}
于 2013-12-06T20:41:19.727 回答