程式的概念是利用改變 PWM (Pulse Width Modulation) 時間佔空比 (Duty Cycle),便可改變供電電壓值到 LED,達到調節 LED 的光暗。程式會由光慢慢地變暗,然後再從暗慢慢地發光,循環這變化。
▲ PIC18F4550 PWM控制LED光暗程式流程圖 |
void main(void) { // 1234567890123456 char LCD_name[] ="BWS PWM - RC1 V1"; char LCD_name2[]=" "; unsigned char dc; // Duty Cycle TRISC = 0b11111001; // Set PORTC C1 and C2 as PWM output LATC = 0b00000000; // Clear PORTC // Initialise LCD OpenXLCD(FOUR_BIT&LINES_5X7); // Init the LCD Display while(BusyXLCD()); WriteCmdXLCD(BLINK_OFF & CURSOR_OFF ); while(BusyXLCD()); stdout = _H_USER; // Redirect I/O to LCD LcdSetLine1(); // Put cursor on start of line 1 putsXLCD(LCD_name); // Display text //Configure CCP module as (PR2+1)*4*TOSC*T2_PS PR2 = 0b10011011; // PWM Frequency = 152 = 2KHz = 0.5ms T2CON = 0b00000111 ; // 1:16 CCP1CON = 0b00001100 ; // PWM Mode P1A/P1C/P1B/P1D=H <5:4> DC CCP2CON = 0b00111100 ; // PWM Mode P2A/P2C/P2B/P2D=H // Duty Cycle CCP1CON<5:4>+CCPR1L while(1) { // PWM resolution is 10 bits don't use last 2 less significant bits CCPxCON, // so only CCPRxL have to be touched to change duty cycle for(dc = 0 ; dc < 128 ; dc++){ CCPR1L = dc ; CCPR2L = 128 - dc ; LcdSetLine2(); // Put cursor on start of line 2 printf("Duty Cycle=%04i", CCPR2L); } for(dc = 127 ; dc > 0 ; dc--){ CCPR1L = dc ; CCPR2L = 128 - dc ; LcdSetLine2(); // Put cursor on start of line 2 printf("Duty Cycle=%04i", CCPR2L); } } // End While } |
▲ LED 會自動慢慢變亮或慢慢變暗 |
▲ Duty Cycle 會自動增加或減少 |
2011 年 04 月 09 日 天氣報告
氣溫:21.9 度 @ 23:00
相對濕度:百分之85%
天氣:天色大致良好
沒有留言:
張貼留言