Random integers?

I’m trying to generate a random integer (0-4). My intention is to leverage that integer as a channel selector. Mostly to try in and learn ESPHOME. I’d rather have it run on the ESP if possible. I’ve been searching, reading, and even Copilot-ing. The closest I can come is the following but the value doesn’t seem to ever come back as an integer. My understanding is random() returns a 32-bit unsigned floating point number between 0.0 and 1.0, multiplied by 5 to return an integer 0-5?

sensor:
 - platform: template
   name: "Random Integer"
   id: random_integer
   update_interval: 3s
   lambda: |-
     return (int(random() * 5));type or paste code here
1 Like

imho int(random()*5) will return mostly 0-4 and return 5 only when random() generate exactly 1.0.

1 Like

Normally you would do a random function, then multiple it with a value to get it to be a integer, like 10, 100, 100 or so on.
After that then you would do %5, which will make an integer division with 5 and return the rest value, which will be the result.

1 Like

This worked for me.

globals:
  - id: random_int_var
    type: int
    restore_value: no
    initial_value: '0'
sensor:
  - platform: template
    name: "Random Int"
    id: random_int
    lambda: |-
      // rand() % (max_number + 1) + minimum_number
      id(random_int_var) = (rand() % (9 + 1)) + 1;
      return id(random_int_var);
    accuracy_decimals: 0
    update_interval: 5s