const int analogPin = A0; // Entrada señal analogica
const int pwmPIN = 9; // Salida digital señal PWM
int pot=512; // almacena la lectura analógica raw del potenciometro
int percent; // posicion del potenciometro en tanto por ciento
const int T=4000; // 25 KHz => Periodo = 40 microsegundos
int Wpulse = T/20; // Ancho del pulso
int last_Wpulse;
void setup() {
Serial.begin(9600);
Serial.println("################################");
Serial.println("####### Generador PWM ##########");
Serial.println("################################");
pinMode(pwmPIN, OUTPUT);
}
void loop() {
pot = analogRead(analogPin); // lectura analógica raw (0-1023)
percent = map(pot, 0, 1023, 0, 100); // convertir a porcentaje (0-100)
Wpulse = T * percent/100; // Ajusta el ancho del pulso segun valor resistencia
if (Wpulse!=last_Wpulse) { // Si se ha modificado el potenciometro
last_Wpulse = Wpulse;
serial(); // imprime cambios
}else{
digitalWrite(pwmPIN, HIGH); // pin ON
delayMicroseconds(Wpulse); // mantiene el valor alto el tiempo Wpulse
digitalWrite(pwmPIN, LOW); // pin OFF
delayMicroseconds(T-Wpulse); // valor bajo durante T-Wpulse
}
}
void serial() {
Serial.print ("Potenciometro = ");
Serial.print (percent, DEC);
Serial.print ("% (");
Serial.print (pot); // valor raw entrada analogica 0-1023
Serial.print (") -> ");
Serial.print (Wpulse);
Serial.println(" microsegundos ");
}
const int T=40000; // 25 KHz => Periodo = 40 microsegundos
us: the number of microseconds to pause. Allowed data types: unsigned int.
This function works very accurately in the range 3 microseconds and up. We cannot assure that delayMicroseconds will perform precisely for smaller delay-times.