int main() { while(1) { motor = 0; //motor switched off for 5 secs wait (5); for (i=0;i<5000;i=i+1) { //5000 PWM cycles, low duty cycle motor = 1; wait_us(400); //output high for motor = 0; wait_us(600); //output low for 600us } for (i=0;i<5000;i=i+1) { //5000 PWM cycles, high duty cycle motor = 1; wait_us(800); //output high for 800us motor = 0; wait_us(200); //output low for 200us } motor = 1; //motor switched fully on for 5 secs wait (5); } } Program Example 4.6: Generating PWM in software /*Program Example 4.7: Plays the tune "Oranges and Lemons" on a piezo buzzer, using PWM */ #include "mbed.h" PwmOut buzzer(p21); //frequency array float frequency[]={659,554,659,554,440,494,554,587,494,659,554,440}; float beat[]={1,1,1,1,1,0.5,0.5,1,1,1,1,2}; //beat array int main() { while (1) { for (int i=0;i<=11;i++) { buzzer.period(1/(2*frequency[i])); // set PWM period buzzer=0.5; // set duty cycle wait(0.4*beat[i]); // hold for beat period } } } Program Example 4.7: and Lemons” program “Oranges
int main() { while(1) { motor = 0; //motor switched off for 5 secs wait (5); for (i=0;i<5000;i=i+1) { //5000 PWM cycles, low duty cycle motor = 1; wait_us(400); //output high for motor = 0; wait_us(600); //output low for 600us } for (i=0;i<5000;i=i+1) { //5000 PWM cycles, high duty cycle motor = 1; wait_us(800); //output high for 800us motor = 0; wait_us(200); //output low for 200us } motor = 1; //motor switched fully on for 5 secs wait (5); } } Program Example 4.6: Generating PWM in software /*Program Example 4.7: Plays the tune "Oranges and Lemons" on a piezo buzzer, using PWM */ #include "mbed.h" PwmOut buzzer(p21); //frequency array float frequency[]={659,554,659,554,440,494,554,587,494,659,554,440}; float beat[]={1,1,1,1,1,0.5,0.5,1,1,1,1,2}; //beat array int main() { while (1) { for (int i=0;i<=11;i++) { buzzer.period(1/(2*frequency[i])); // set PWM period buzzer=0.5; // set duty cycle wait(0.4*beat[i]); // hold for beat period } } } Program Example 4.7: “Oranges and Lemons” program
Code%20snips_Ch_4.docx