Electronic – Separating a PORT into in/out and getting random nums

adcatmegaportrandom numberuart

Using ATMega1284

I want to generate a random number from 0-7 (maybe more range). This is the main concern. As long as it "feels" random its fine. And it could resolve the rest of my issues… anyways

My approach?
I could seed a number off of the ADC port (PORTA in ATMega1284).
This causes me to clear up PORTA for the ADC. But I still need to get another 8 outputs connected.

PORTA has ADC (1/8 pins used)
PORTB is full (8/8 pins used)
PORTC is full (8/8 pins used)
PORTD has USART on (2/8 pins used)

I still need 8 pins for output and each port is doing its thing. So could I split PORTA and PORTD so I could connect 8 more pins? how would I do this when I have UART and ADC enabled?

OR

If someone could provide an internal/better way of getting a random number. It could solve the issue entirely

Best Answer

Why are you not using the rand() function from the avr standard libraries?

Library documentation, stdlib.h

void function() { PORTD = (uint8_t)rand(); }

In the second part of your question, just split them up. If you can use pins 2, 3, and 4 of PORTA, do:

PORTA = randonNumber & ( (1 << 1) | (1 << 2) | (1 << 3) );

Basically I would suggest for you to study the different ways in which you can map source bits to destination bits in C through the use of bitwise operators.