In the code below you will find the following "analogWrite(ledPin2, random(120)+135);".
Can someone please tell me what is going on in this line of code? I looked up the function but it did not reference the above format for the random function. Specially, (120)+135. What is going on there?
Programming is "synthetic", i.e. you are building systems. Of course, you can not find examples of the trillion trillion trillion possible ways you can put together expressions. What you can understand, is the rules for putting expressions together, then you can analyze an existing expression. Without this ability to analyze, not only can you not read code, you can't really code.
There is no single fixed "format" for things that have almost infinite options. Only rules.
In this case, it is the order of operations, parentheses after a function name take precedence over their use in an arithmetic expression. It's the same in math. sin(x)/x is not sin((x)/x)).
It is a feature of random() that I did not know about.
TBC random is available to be called with one OR two parameters.
The original was perhaps written by someone who is more familiar with C and so just did a little math to shift regular old one parameter random()’s output range by a subsequent addition.
Which we assume would be seen in the code of the two parameter code of random(). A random number between 0 and (max - min) is added to min.
Either works, the first is what I would get right away, the modern version would make me go look at the documentation, which is never a bad thing but it is a thing.
I’d still probably never remember that and do the way it was when my brain was more, er, flexible.
It's a little odd that they stop at 254 (the upper limit on random() is 'exclusive'). random(120) never returns 120. Perhaps it was intentional for some reason but I think it is likely that they didn't know that the upper limit was not included in the range and they wanted random(121) + 135 or maybe random(120) + 136 (equivalent to random(135, 256) and random(136, 256) respectively).