The reason to use values 0-240 rather than the usual 0-255 is because the last 15 colors will ‘wrap around’ from the end to the start of the palette. Sometimes this wrapping (circular blending) is useful as it keeps things smooth, other times (in your case here) it’s not what you want.
If you want to still code using a 0-255 range but have the output maximum be 240 you can use the scale8 function:
scale8( i , 240 )