higher Frequency

hi guys, i wrote a code:

int x,y;
void setup()
{
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  randomSeed(analogRead(A0)); ;
}

void loop()
{
  x=random(0,2);
  y=random(0,2);
  digitalWrite(8,x);
  digitalWrite(9,y);
  delayMicroseconds(100);
}

it supposes to be like generate random pseudo sequence with 10Khz...well the result is random yet the frequency is just like 4KHz. anyway could make it 10Khz?Thansks

your random and digitalWrites take time, too. reduce delayMicroseconds to adjust. or look into blink without delay to get more accurate.

For 10KHz, you signal must go hi & low every 50 microseconds.
digitalWrite also takes time, you could replace those with direct port manipulation.

  x=random(0,2);
  y=random(0,2);
if(x==0){
PORTB = PORTB & B11111110;  // clear D8
}
else{
PORTB = PORTB | B00000001; // set D8
}
if (y == 0){
PORTB = PORTB & B11111101; // clear D9
}
else {
PORT = PORT| B00000010; // set D9
}
  delayMicroseconds(50);

Replace PORTB with the correct port if needed.

Unfortunately, your random(0, 2) calls are taking 141 microseconds each. You'll need a faster pseudo-random generator.

This thread seems vaguely familiar. See this thread.

and generate 10khz signal - Programming Questions - Arduino Forum

The random pseudo sequence (white noise) is usually generated by shift registers with an XORed feedback (from a few shiftreg bits). My old pic12c508 @4MHz does 20kHz in asm (~10hrs random seq period, afair), so arduino could be faster..

http://www.elektronik-labor.de/AVR/dds/Noise.html

For example (an example of a 32-bit maximal period Galois LFSR from wikipedia above):

void setup() {
  // put your setup code here, to run once:
 Serial.begin(115200);
}

void loop() {
  // put your main code here, to run repeatedly: 
  
unsigned long lfsr = 1u;
unsigned bit;
unsigned long period = 0;

long t = micros();

do {
  /* taps: 32 31 29 1; feedback polynomial: x^32 + x^31 + x^29 + x + 1 */
  lfsr = (lfsr >> 1) ^ (-(lfsr & 1u) & 0xD0000001u); 
  ++period;       // remove this in your code
  if (period==10000) Serial.println(micros()-t);  //  << remove this in your code then, put here the bit output
} while(lfsr != 1u);

  period = 0;
}

Prints:

35844

So a loop takes 3.58usecs. It takes less when you remove the print line there, but you have output a bit so it might be the same (or even shorter) :wink:

The actual loop:

unsigned long lfsr = 1u;
for(;;) {
  /* taps: 32 31 29 1; feedback polynomial: x^32 + x^31 + x^29 + x + 1 */
  lfsr = (lfsr >> 1) ^ (-(lfsr & 1u) & 0xD0000001u); 
  // << HERE do output a bit to an output pin
  // << HERE put a delay when required
}

The pseudo random seq period will be ~4.2hours.
A discussion on that algorithm: Talk:Linear-feedback shift register - Wikipedia
Not tested, no warranties of any kind :slight_smile: