Skip to content

Commit 9c83ea0

Browse files
committed
add random functions. literally.
1 parent 258971c commit 9c83ea0

File tree

4 files changed

+36
-0
lines changed

4 files changed

+36
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
1010
- Support for all builtin Bits and Bytes functions https://www.arduino.cc/reference/en/
1111
- Support for GODMODE and time functions
1212
- Support for Character functions https://www.arduino.cc/reference/en/
13+
- Support for `random` functions with seed control
1314
- Many original Arduino `#define`s
1415

1516
### Changed

SampleProjects/TestSomething/test/good-godmode.cpp

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,16 @@ unittest(millis_micros_and_delay)
1515
assertEqual(14000, micros());
1616
}
1717

18+
unittest(random)
19+
{
20+
randomSeed(1);
21+
unsigned long x;
22+
x = random(4294967293);
23+
assertEqual(4294967292, x);
24+
x = random(50, 100);
25+
assertEqual(83, x);
26+
x = random(100);
27+
assertEqual(74, x);
28+
}
29+
1830
unittest_main()

cpp/arduino/Arduino.cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,20 @@ void delay(unsigned long millis) {
2121
void delayMicroseconds(unsigned long micros) {
2222
godmode.micros += micros;
2323
}
24+
25+
26+
void randomSeed(unsigned long seed)
27+
{
28+
godmode.seed = seed;
29+
}
30+
31+
long random(long vmax)
32+
{
33+
godmode.seed += 4294967291; // it's a prime that fits in 32 bits
34+
return godmode.seed % vmax;
35+
}
36+
37+
long random(long vmin, long vmax)
38+
{
39+
return vmin < vmax ? (random(vmax - vmin) + vmin) : vmin;
40+
}

cpp/arduino/Arduino.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,15 @@ Where possible, variable names from the Arduino library are used to avoid confli
99
class GodmodeState {
1010
public:
1111
unsigned long micros;
12+
unsigned long seed;
1213

1314
void resetClock() {
1415
micros = 0;
1516
}
1617

1718
void reset() {
1819
resetClock();
20+
seed = 1;
1921
}
2022

2123
GodmodeState() {
@@ -87,6 +89,10 @@ inline unsigned int makeWord(unsigned char h, unsigned char l) { return (h << 8)
8789

8890
#define word(...) makeWord(__VA_ARGS__)
8991

92+
// random
93+
void randomSeed(unsigned long seed);
94+
long random(long vmax);
95+
long random(long vmin, long vmax);
9096

9197

9298
// Time

0 commit comments

Comments
 (0)