Lesson 87: Using sin() Function
Learn how sin() creates smooth periodic values from angles for wave motion, animation, and timing patterns.
Progress indicator
Lesson 87 of 87
Learning Objectives
- Understand what sin() calculates and why it produces smooth repeating values.
- Learn the correct sin() syntax and why angle input must be in radians.
- Understand sin() return range and how to map it safely to hardware output ranges.
- Apply sin() in PWM-based LED animation and cyclic embedded control patterns.
- Avoid common beginner mistakes like using degrees directly or skipping normalization.
- Read waveform behavior from Serial values and connect math output to visible LED changes.
Concept Explanation
What is sin()
sin() computes the sine of an angle. Sine is a trigonometric function that produces a smooth repeating waveform.
The output continuously moves between -1 and 1. This natural wave behavior is useful for breathing LEDs, smooth motion patterns, and periodic control values.
Think of sine as a software waveform generator. As the angle increases little by little, the output rises gradually, peaks, falls, reaches a minimum, and rises again. This smooth cycle is exactly why sine is widely used in beginner animation and signal demos.
sin() Syntax
Basic syntax: sin(angleInRadians)
sin(0)returns 0sin(PI / 2)returns near 1sin(PI)returns near 0
One full sine cycle is completed between 0 and 2 * PI. After that, the same pattern repeats forever.
How sin() Works
- Take an angle value in radians.
- Compute sine through the math library.
- Return a floating-point result in the range -1 to 1.
When angle increases in small steps, sine changes smoothly. One full cycle is from 0 to 2 * PI.
If your step size is too large, the signal looks jumpy. If your step size is small and your delay is stable, the signal looks smooth and predictable.
Radians vs Degrees
sin() expects radians, not degrees. Convert degrees first: radians = degrees * PI / 180.0.
- 0 degrees = 0 rad
- 90 degrees = PI/2 rad
- 180 degrees = PI rad
Passing degree numbers directly is one of the most common beginner mistakes. If your output looks wrong, check your angle unit first.
sin() Return Value
sin() returns from -1.0 to 1.0. Hardware PWM needs 0..255, so convert range before writing to output.
A common mapping is (sinValue + 1.0) * 0.5 to get 0.0..1.0, then multiply by 255.0 for PWM.
This mapping keeps all results valid for LED brightness. Without this step, negative values can produce invalid or confusing hardware behavior.
When to Use sin()
- Smooth LED breathing and fading animations.
- Periodic motion signals for cyclic control logic.
- Wave-based timing/shape generation in embedded experiments.
- Any case where gradual smooth change is better than hard ON/OFF jumps.
Real-life example: status LEDs in devices often "breathe" while connecting to WiFi. That smooth effect can be built using the same sine-to-PWM pattern shown here.
Example Code
This example uses sin() output to create a smooth LED brightness wave.
const int LED_PIN = 2;
float angleRad = 0.0;
void setup() {
pinMode(LED_PIN, OUTPUT);
Serial.begin(115200);
}
void loop() {
// Move angle forward in small radian steps.
angleRad = angleRad + 0.20;
if (angleRad > 6.283185) { // 2 * PI
angleRad = 0.0;
}
float wave = sin(angleRad); // range: -1.0 to 1.0
float normalized = (wave + 1.0) * 0.5; // range: 0.0 to 1.0
int pwmValue = (int)(normalized * 255.0);
pwmValue = constrain(pwmValue, 0, 255);
analogWrite(LED_PIN, pwmValue);
Serial.print("angle(rad): ");
Serial.print(angleRad, 2);
Serial.print(" | sin: ");
Serial.print(wave, 3);
Serial.print(" | pwm: ");
Serial.println(pwmValue);
delay(120);
}Example Code Explanation
- Set pin 2 as output so LED brightness can be controlled.
- Increase angleRad each loop to move along the sine curve.
- Wrap angle back to 0 after
2*PIto keep repeating cycles. - Use
sin(angleRad)to get a smooth value between -1 and 1. - Normalize that value to 0..1 so it can be used for PWM output mapping.
- Scale normalized value to 0..255 and constrain to protect output range.
- Write PWM to LED pin so brightness follows the sine wave.
- Print angle, sine value, and PWM value to Serial for debugging.
- When sine is near
1, PWM is near 255 (bright). When sine is near-1, PWM is near 0 (dim). delay(120)sets update pace; reducing it can make transitions look smoother.
What Happens Inside
- CPU updates angle variable in RAM on every loop iteration.
- Math routine computes sine from current angle in radians.
- Result is remapped from -1..1 to 0..1.
- Program scales value into PWM byte range 0..255.
- PWM duty cycle register is updated with mapped value.
- LED brightness appears to rise/fall smoothly over time.
- Serial buffer receives debug messages for each cycle.
- Loop repeats forever, continuing the same waveform behavior.
Common Mistakes with sin()
- Passing degree values directly to sin() without converting to radians.
- Using raw -1..1 sine output directly in PWM writes.
- Skipping angle wrap, causing long-run drift and harder debugging.
- Using very large angle steps, making output jump instead of smooth.
- Not checking output bounds before writing hardware values.
Best Practices for sin()
- Always use radians and document conversion clearly in code comments.
- Normalize sine output before converting to PWM or other output ranges.
- Use small angle steps for smooth motion and predictable wave behavior.
- Clamp outputs using constrain() before sending values to hardware.
- Use Serial prints during tuning to verify angle, wave, and mapped output values.
Try it now
Open the simulator workspace and observe how sine values map into smooth LED brightness changes.