Greetings, I'm trying to control the Duty-Cycle of a PWM by typing a number into the serial monitor. I'm having trouble trying to achieve this. Can anyone give me some advice, please? Here is the code:
void pwm_init1()
{
int x = Serial.read(); // Read the number we received
TIMSK1 = 0;
TCNT1 = 0;
ICR1 = 780;
OCR1A = x; // Duty - Cycle
DDRB |= (1 << DDB5); // PB5 ( OC1A/PCINT5 ) | digital pin 11 (PWM) (https://www.arduino.cc/en/Hacking/PinMapping2560)
TCCR1A = (1 << COM1A1) | (0 << COM1A0) | (1 << WGM11) | (0 << WGM10); // inverting PWM on OC1A, PWM Phase Correct, TOP = ICR1
TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS12) | (0 << CS11) | (1 << CS10);
}
int main() {
Serial.begin(115200);
cli();
sei();
while (1)
{
if (Serial.available()) pwm_init1(); // Just loop looking for user input
}
}
The reason I'm programming the PWM from the register is that it gives me easy control of the frequency.
Pert! Thank you for the suggestion! I will try it.
Paul, I want to control the DC and f because I want the user to be able to modify the PWM signal in order to adjust the LEDs that stimulate a sample during an experiment.
chiesadoc:
Paul, I want to control the DC and f because I want the user to be able to modify the PWM signal in order to adjust the LEDs that stimulate a sample during an experiment.
Paul. As it is configured in the register, the frequency right now is 20 Hz. Controlling the frequency will change the behavior of the LED. Maybe you didn't read it in the message before because I typed "f".
I think it's solved now, here is the code in case someone is lurking around:
long i;
// Echos input from the serial monitor
void setup() {
Serial.begin(115200);
while (!Serial) {}
Serial.println("hello");
Serial.setTimeout(10);
}
void loop() {
if (Serial.available() > 0) {
i = Serial.parseInt();
Serial.print("i = ");
Serial.println(i);
}
}