float t = 0;
float f = 100; //frecuencia
float p = 1/f; //periodo
unsigned long oldMicros = 0;
unsigned long nowMicros = 0;
const byte PRESCALER2 = 0b001;
void setup() {
Serial.begin(115200);
//ajusta la frec. salida PWM pin 3
TCCR2B = (TCCR2B & 0b11111000) | PRESCALER2;
pinMode(3, OUTPUT);
}
double dt = 0;
double tf = 0;
double signal = 0;
void loop() {
nowMicros = micros();
dt = double(nowMicros - oldMicros)/1000000;
t += dt;
tf = t*f;
//Distintas señales a elegir
//signal = tf; //dientes de sierra
//signal = (sin(tf*2*PI)+1)/2 ; //seno
//signal = sin(tf*PI); //seno positiva
signal = (sin(tf*2*PI) > 0) ? 1: 0; //cuadrada
//signal = (sin(tf*2*PI) >= 0) ? 2*tf: 2-(2*tf); //triangular
byte value = byte(255 * signal);
analog(value);
oldMicros = nowMicros;
//cuando alcanza un periodo se reinicia
if(t >= p){
t = 0;
}
}
//compensa el desajuste de la salida analogica
void analog(byte value){
value += (255 - value) >> 4;
analogWrite(3, value);
Serial.print(value);
}