Formula for producing numbers between 0 and 255? I'm writing a program that needs to cycle through numbers between 0-255 given mouse X position. If given number goes over 255, the difference should be subtracted, as in 0,1,2...255,254,253...3,2,1,0,1,2,3,4...255,254...

For example

Given  Output
  1      1
  2      2
 255    255
 256    254
 509     0
 510     1


I've been toying with different formulas (x mod 255) is close but when it goes over 255, goes straight to 0 rather than 254. 

Another one I came up with was round( 127.5*cos(x/16)+127.5 ) it produced decent numbers but not good enough.

Am I making this too complicated? What is a formula that can produce numbers like this?
Here's a detailed solution which works for $5$ instead of $255$, but I easily extended it to your need at the end.

Let's start with a function $f(x) = x$. For $1$ to $9$ you get :

$1,2,3,4,5,6,7,8,9$ 

Then with $x-5$, you get :

$-4,-3,-2,-1,0,1,2,4,5$ 

With $\sqrt{(x-5)^2}$ you get :

$4,3,2,1,0,1,2,3,4$

Then $5-\sqrt{(x-5)^2}$ gives you :

$1,2,3,4,5,4,3,2,1$.

For $5$, the final formula is $f(x) = 5-\sqrt{(\bmod(x,9)-5)^2}$
For $255$, your final formula is then  $f(x) = 255-\sqrt{(\bmod(x,509)-255)^2}$ !

PS : I saw you using PHP so here's the PHP equivalent : 

return 255-abs((x%509)-255)
As a single function:
$$\mathrm{sgn}\left(\sin(\dfrac{\pi x}{255})\right)x \pmod{255}$$

Or piecewise:
$$*\left\{\begin{matrix}
x \pmod {255} &amp;&amp;&amp;1\leq x\leq 255 \mod (510)\\
-x \pmod {255} &amp;&amp;&amp;256\leq x\leq 510 \mod (510)
\end{matrix}\right.$$

I think these should work.