Added hardware random option and added function to set seed

This commit is contained in:
Dreaded_X 2021-01-16 01:34:57 +01:00
parent 228856c26d
commit 6e2ab11578
4 changed files with 57 additions and 32 deletions

View File

@ -13,7 +13,7 @@ ASFLAGS = -plosgff
SRC = \
src/crt0.s \
src/bios.s \
src/random.s \
src/random.c \
src/console.c \
OBJ_1 = $(notdir $(SRC:.c=.rel))

View File

@ -1,3 +1,11 @@
#include "types.h"
// Get a pseudo random number
uint8_t random();
// Set the seed for the random number generator
void random_set_seed(uint8_t seed);
// Get a random number from hardware
uint8_t random_hw();

48
src/random.c Normal file
View File

@ -0,0 +1,48 @@
#include "random.h"
uint8_t random_seed;
// Fast RND
//
// An 8-bit pseudo-random number generator,
// using a similar method to the Spectrum ROM,
// - without the overhead of the Spectrum ROM.
//
// R = random number seed
// an integer in the range [1, 256]
//
// R -> (33*R) mod 257
//
// S = R - 1
// an 8-bit unsigned integer
uint8_t random() __naked {
__asm
ld a, (_random_seed)
ld b, a
rrca ; multiply by 32
rrca
rrca
xor #0x1f
add a, b
sbc a, #255 ; carry
ld (_random_seed), a
ld l, a
ret
__endasm;
}
void random_set_seed(uint8_t seed) {
random_seed = seed;
}
uint8_t random_hw() __naked {
__asm
in a, (0x09)
ld l, a
ret
__endasm;
}

View File

@ -1,31 +0,0 @@
; Fast RND
;
; An 8-bit pseudo-random number generator,
; using a similar method to the Spectrum ROM,
; - without the overhead of the Spectrum ROM.
;
; R = random number seed
; an integer in the range [1, 256]
;
; R -> (33*R) mod 257
;
; S = R - 1
; an 8-bit unsigned integer
.area _CODE
_random::
ld a, (_random_seed)
ld b, a
rrca ; multiply by 32
rrca
rrca
xor #0x1f
add a, b
sbc a, #255 ; carry
ld (_random_seed), a
ld l, a
ret