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?
1 Answer 1
Your problem seems to be related to how you get the actual length you want to generate. There are other ways you could do that. Since your max seems to be 4 characters, you could possibly enter "9999" which would overflow the 50 bytes temp
variable.
You could simply read until \n
and then atoi
. Then cap at 50.
As a side note, here's a function I've used in the past to generate (pseudo)random strings for network requests (e.g. state
or nonce
parameters)
#define MAX_UID 8 /* Change to whatever length you need */
const char * generateUID(){
/* Change to allowable characters */
const char possible[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
static char uid[MAX_UID + 1];
for(int p = 0, i = 0; i < MAX_UID; i++){
int r = random(0, strlen(possible));
uid[p++] = possible[r];
}
uid[MAX_UID] = '0円';
return uid;
}
Explore related questions
See similar questions with these tags.
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.