Basic Increment and Decrement [Solved]

Basically, I’m trying to get value Y to increment to 180 and then decrement to 0 repeatedly.

0-180 180-0 0-180…

I had an idea of using sin(x) = y. And then X++ increments.

I’m having trouble coding this, Heres what I Have.

int x = 0;
int y = 0;
 
void setup() 
{ 
  Serial.begin(9400);
} 
 
 
void loop() {
  x++;
  if (x >= 180)
  {
    x = 0;
  }
  y = sin(x);
  Serial.println(y);
}

If i can get the sin working I will multiply “y” by a factor to get my 0-180.

I know on the reference page it says serial.println does not support floats but the Serial won’t even print “1” when x = 90.
All i get is never ending zeros as the value of y.

Is there perhaps something wrong in the code?
Is there a different way to approach the solution?

This seems very basic :smiley: im just not getting it ::slight_smile:

If sin worked, the increment would not be linear. Does that matter?

If all you want is for Y to change uniformly, create an int, delta. Set it to +1.

if(delta > 0)
{
   y++;
   if(y > 180)
   {
       y = 0;
       delta = -1;
   }
}
else
{
   y--;
   if(y < 0)
   {
       y = 0;
       delta = 1;
   }
}

If you're going to use sin(), you really need to use floating point numbers. Even if sin(90) returned 0.9999912, your program would print 0.

Also, the argument to sin() is a value in radians!

Genius Paul!

I never thought of using something sort of like a switch
(changing +1 to -1)

Thanks! This helps me in accelerating and decelerating my servo.

Final code:

int delta = 1;
int y = 0;

void setup() {
  Serial.begin(1200);
}


void loop() {
if(delta > 0)
{
   y++;
   if(y >= 180)
   {
       delta = -1;
   }
}
else
{
   y--;
   if(y <= 0)
   {
       delta = 1;
   }
} 
Serial.println(y);
}

*********************** Problems Solved *********************