/* LAB 2: LED Bit Arithmetic */ /* LED Pins * * We use output pins { start_led, ... , (start_led+num_bits-1) } to drive * the display LEDs. The pins are ordered from low bit 0 (on the right) * to the high bit 7 (on the left). */ uint8_t start_led = 6; uint8_t num_bits = 8; void setup() { /* Set each pin connected to an LED to output mode */ for(uint8_t i = 0; i < num_bits; i++){ pinMode(start_led + i,OUTPUT); } Serial.begin(9600); } void loop() { /* Read a number from the serial port and display the number with the 8 LEDs */ int32_t recv = readint(); Serial.println(recv); display_1(recv); // display_2(recv); // display_3(recv); } /* QUESTION #1: This is not very good code. Why? */ void display_1 (int input) { if (0x0001 & input) { digitalWrite(start_led + 0, HIGH);} if (0x0002 & input) { digitalWrite(start_led + 1, HIGH);} if (0x0004 & input) { digitalWrite(start_led + 2, HIGH);} if (0x0008 & input) { digitalWrite(start_led + 3, HIGH);} if (0x0010 & input) { digitalWrite(start_led + 4, HIGH);} if (0x0020 & input) { digitalWrite(start_led + 5, HIGH);} if (0x0040 & input) { digitalWrite(start_led + 6, HIGH);} if (0x0080 & input) { digitalWrite(start_led + 7, HIGH);} } /* QUESTION #2: This is an alternative version of the display_1 code that is more general. Why? */ void display_2 (int32_t input) { int16_t mask = 0x0001; for (int8_t i=0; i < num_bits; i++) { if ( (mask << i) & input) { digitalWrite(start_led + i, HIGH); } } } /* Another alternative version of display_1. */ void display_3 (int32_t input) { int16_t mask = 0x0001; for (int8_t i=0; i < num_bits; i++) { if (mask & input) { digitalWrite(start_led + i, HIGH); } /* QUESTION #3: You can use either of these two. Why? * mask = mask << 1; * or * input = input >> 1; * * QUESTION #4: What happens if the sign bit of the input is * set? */ input = input >> 1; } } /* Read an integer off of the serial port and return. */ int32_t readint() { char s[128]; /* 128 characters should be more than enough. */ readline(s, 127); s[127] = '\0'; return atoi(s); } /* Read a line (up to maxlen characters) off of the serial port. */ void readline(char *s, uint8_t maxlen) { uint8_t i = 0; while(1) { while (Serial.available() == 0) { } /* Do nothing */ s[i] = Serial.read(); if (s[i] == '\0' || s[i] == '\n' || i == maxlen-1) break; i += 1; } }