I am not comfortable the way you generated your triangular wave. It seems like your code would generate 'temp' in the sequence 0,...,511,511,...,0,0,...,511,511,...,0,0,...
Your integer range is -512 to +511.
Why not use SIGNED data type, reset to 0, and then alternately increase to upper...