PWM control LED source code

Publisher:静心静气Latest update time:2022-12-27 Source: zhihuKeywords:LED  ATTiny13 Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere

// Cpu ATTiny13

// Frequency: Internal 9.6000Mhz without frequency division

// winavr gcc optimization level O0

#include


#define nop() __asm__ __volatile__("nop") //Empty statement


unsigned char PWM[]={0x20,0x40,0x60,0x80,0xA0,0xC0,0xE0,0xFF};

unsigned char PWMON;

unsigned char PWMVal;


//IO pin initialization 

void port_init(void)

{

PORTB = 0x08; //PB3 connected button is set to output pull-up

DDRB = 0x37; //PB0 is set to 0 when the PWM output is powered on

}


//Timer0 initialization

//Fast PWM mode frequency 37.500KHz

void timer0_init(void)

{

OCR0A = 0x00;

TCNT0 = 0x01; //Design number

TCCR0A = 0x03; //Set Timer0 to fast PWM mode

TCCR0B = 0x01; //Start Timer0

}


//Delay N milliseconds

void delay_ms(void)

{

unsigned char TempCycA;

unsigned char TempCycB;


for (TempCycA=0; TempCycA<10; TempCycA++)

for (TempCycB=0; TempCycB<90; TempCycB++)

nop();

}


//Main function

int main(void)

{

unsigned int tempval=0;

unsigned int keytime=0;


port_init();

timer0_init();


PWMON = 1; //Initially PWM is on

PWMVal = 0; //First gear

OCR0A = PWM[PWMVal]; //Change the duty cycle

TCCR0A = 0x83; //Turn on PWM


while(1)

{

if (!(PINB&0x08))

{

keytime = 0;

for (tempval=0; tempval<4000; tempval++)

{

if (!(PINB&0x08)) //Key sampling, anti-shake

{

keytime++;

delay_ms();

}

else

break;

}

}


if (PWMON) //When PWM is on

{

if ((keytime>100)&&(keytime<1000)) //Short press 100-1000ms to adjust

{

PWMVal++;

if (PWMVal>7) //Loop

PWMVal = 0;

keytime = 0;

OCR0A = PWM[PWMVal]; //Change the duty cycle

}

if (keytime>2999) //Long press for 3 seconds to turn off

{

PWMON = 0;

keytime = 0;

TCCR0A = 0x03; //Turn off PWM

delay_ms(); //Delay

}

}

else //When PWM is turned off

{

if (keytime>2999) //Long press for 3 seconds to turn on

{

PWMON = 1;

keytime = 0;

TCCR0A = 0x83; //Turn on PWM

}

}

}

}


Keywords:LED  ATTiny13 Reference address:PWM control LED source code

Previous article:How to build a digital keypad security door lock using Arduino
Next article:Design of wireless sensor network nodes based on microcontroller and wireless communication module

Latest Microcontroller Articles
Change More Related Popular Components

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号