Consider a microcontroller port with a direction register (DDR) and a data register (PORT). The DDR controls pin direction (1 for output, 0 for input). The PORT register controls output value if the pin is output, or enables pull-up resistor if input.
What will be the output on the port pins after running this code?
#include <stdint.h> #include <stdio.h> uint8_t DDR = 0x00; // Direction register uint8_t PORT = 0x00; // Data register int main() { DDR = 0b00001111; // Lower 4 pins output, upper 4 pins input PORT = 0b10101010; // Set alternating bits // Simulate reading port pins uint8_t pin_values = PORT & DDR; // Output pins show PORT value printf("Pin values: 0x%02X\n", pin_values); return 0; }
Remember that only pins set as output in DDR show the PORT value on pins.
The DDR sets lower 4 pins as output (bits 0-3). PORT is 0b10101010. Masking PORT with DDR (0b00001111) keeps only lower 4 bits: 0b00001010 (0x0A). So output pins show 0x0A.
Choose the correct description of the roles of the Direction Register (DDR) and Data Register (PORT) in microcontroller I/O ports.
Think about what controls if a pin is input or output, and what controls the voltage level.
DDR configures pins as input or output. PORT sets output voltage for output pins or enables pull-up resistors for input pins.
The code below tries to set pins 0-3 as outputs and set them high, but the output pins remain low. What is the cause?
#include <stdint.h> #include <stdio.h> uint8_t DDR = 0x00; uint8_t PORT = 0x00; int main() { DDR = 0b00001111; // Set pins 0-3 as output PORT = 0b00001111; // Set pins 0-3 high // Simulate reading pins uint8_t pins = PORT & DDR; printf("Pins: 0x%02X\n", pins); return 0; }
Think about what DDR and PORT represent in real embedded systems versus this simulation.
DDR and PORT here are just variables, not actual hardware registers. Setting them does not affect real pins. In real embedded code, these would be memory-mapped registers.
Analyze the following embedded C code snippet. What error will it produce when compiled?
#include <stdint.h> uint8_t DDR = 0x00; uint8_t PORT = 0x00; int main() { DDR = 0b00001111; PORT = 0b10101010; return 0; }
Check each line carefully for missing punctuation.
The line 'DDR = 0b00001111' is missing a semicolon at the end, causing a syntax error.
Given the following code, how many pins are configured as output and set to high voltage?
#include <stdint.h> uint8_t DDR = 0b11001100; uint8_t PORT = 0b10101010; int main() { uint8_t output_pins = DDR & PORT; int count = 0; for (int i = 0; i < 8; i++) { if ((output_pins >> i) & 1) { count++; } } return count; }
Count bits set to 1 in DDR and PORT at the same positions.
DDR = 0b11001100 (bits 7,6,3,2 set as output). PORT = 0b10101010 (bits 7,5,3,1 set). DDR & PORT = 0b10001000 (bits 7,3 set). The loop counts 2 pins.