Jump to content

Recommended Posts

I have 20 leds and I want them to twinkle at random using a 12F629.

My subroutine accepts an unsigned char between 1 & 20.

The program is fine, no errors and blinks a lot of patterns except my random part.

I have included rand...16...lib with no problems


rand() returns unsigned short so it is 16 bits? or 0 to 65535? or is it a fraction between 0 & 1 like the rest of my world?


I thought I could use unsigned char y = 20*rand() + 1; but it does not work.

I also tried unsigned char y = 20*rand()/65535; with all sorts of tries at parenthesis to deal with possible overflows and such.


All the info about rand in BoostC talks about the function not the results.

How can I use the rand() result to get an integer number from 1 to 20 and convert that to unsigned char?

I am guessing that division is always returning a zero somewhere. :unsure:


Any clues? Xmas is coming.

Link to post
Share on other sites
How about


y = (rand() % 19) + 1;


rand returns a short (unsigned int).






Many most humble thankyous :unsure:

In a past life I used to teach introductory programming at university.

Oldtimer's disease must be setting in early; I'm not even 52 yet.


It works great with y = rand()%20+1;


Mod 20 gives 20 remainders and +1 shifts from 0-19 up to 1-20.


Link to post
Share on other sites

Join the conversation

You are posting as a guest. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...