I'm trying to build arduino nonce generator, but the only thing I found is this question on arduino forum but I can't find out how to make it work for me. I checked and Serial.available() is always 0 for me and if I delete the If I still get nothing
My code:
void setup() {
Serial.begin(9600);
randomSeed(analogRead(0));
}
void loop() {
byte randomValue;
char temp[5];
char letter;
char msg[50]; // Keep in mind SRAM limits
int numBytes = 0;
int i;
int charsRead;
if(Serial.available() == 0)
{
charsRead = Serial.readBytesUntil('\n', temp, sizeof(temp) - 1); // Look for newline or max of 4 chars
temp[charsRead] = '\0'; // Now it's a string
numBytes = atoi(temp);
if(numBytes > 0)
{
memset(msg, 0, sizeof(msg));
for(i = 0; i < numBytes; i++) {
randomValue = random(0, 36);
msg[i] = randomValue + 'a';
if(randomValue > 26) {
msg[i] = (randomValue - 26) + '0';
}
}
Serial.println("Here is your random string: ");
Serial.println(msg);
Serial.print("I received: ");
Serial.println(numBytes);
delay(1000);
}
}
}
How do I make it work?
Do you have some working random alphanumeric string generator that you are using?
if(Serial.available() == 0)
? If you want to read data fromSerial
you should check forif(Serial.available() > 0)
, which can be written shorter asif(Serial.available())
. Please try thatif(randomValue > 26)
should beif(randomValue >= 26)
. Other than the fixes suggested in these three comments, the sketch should work as advertised.