#include<avr/io.h>
#include<avr/interrupt.h>
#include"microPLC.h"
unsigned int microPLC::ms=0;ISR(TIMER1_COMPA_vect){microPLC::ms++;}microPLC::microPLC(){}void microPLC::init(void){cli();TCCR1A=0;TCCR1B=0;OCR1A=624;TCCR1B|=(1<<WGM12);TCCR1B|=(1<<CS12);TIMSK1|=(1<<OCIE1A);sei();}int Counter::Con(void){return con;}void Counter::N(int n_){n=n_;}void Counter::Set(bool s_){if(s_==1&&s==0){con=n;if(n==0)q=0;else q=1;}s=s_;}void Counter::Reset(bool r_){if(r_==1&&r==0){con=0;q=0;}r=r_;}bool Counter::Q(void){return q;}bool Counter::D(void){if(con>=fin)return 1;else return 0;}Counter::Counter(){n=0;con=0;q=0;r=0;fin=1000;}Counter::Counter(int n_,int fin_){n=n_;con=n;q=0;r=0;fin=fin_;}void CI::Inc(bool i_){if(i_==1&&i==0){if(con<fin){con++;q=1;}}i=i_;}void CD::Dec(bool d_){if(d_==1&&d==0){if(con>0){con--;}else q=0;}d=d_;}void CID::Dec(bool d_){if(d_==1&&d==0){if(con>0){con--;}else q=0;}d=d_;}Timer::Timer(){tb=T1S;t=1;ms2=0;q=0;s=0;r=0;}Timer::Timer(int t_,int tb_){TBase(tb_);Time(t_);ms2=0;q=0;s=0;r=0;}void Timer::Time(int t_){if(t_)t=t_;else t=1;}void Timer::TBase(int tb_){switch(tb_){case T10MS:case T100MS:case T1S:tb=tb_;break;default:tb=T1S;}}void Timer::Reset(bool r_){if(r_==1&&r==0){q=0;on=0;}r=r_;}bool Timer::T(void){return on;}void Timer::timerAVR(void){if(microPLC::ms>ms2){tt+=(microPLC::ms-ms2);ms2=microPLC::ms;}if(microPLC::ms<ms2){tt+=(0xFFFF-ms2);tt+=microPLC::ms;ms2=microPLC::ms;}}void TI::Set(bool s_){if(s_==1&&s==0){tt=0;ms2=microPLC::ms;on=1;q=1;}s=s_;if(s_==0){q=0;on=0;}}bool TI::Q(void){timer();return q;}void TI::timer(void){if(on){timerAVR();if(tt>=t*tb){q=0;on=0;}}}void TIP::Set(bool s_){if(s_==1&&s==0){tt=0;ms2=microPLC::ms;on=1;q=1;}s=s_;}void TRC::Set(bool s_){if(s_==1&&s==0){tt=0;ms2=microPLC::ms;on=1;q=0;}s=s_;if(s_==0){q=0;on=0;}}bool TRC::Q(void){timer();return q;}void TRC::timer(void){if(on){timerAVR();if(tt>=t*tb){q=1;on=0;}}}void TRCM::Set(bool s_){if(s_==1&&s==0){tt=0;ms2=microPLC::ms;on=1;q=0;}s=s_;}void TRD::Set(bool s_){if(s_==1&&s==0){on=0;q=1;}if(s_==0&&s==1){tt=0;ms2=microPLC::ms;on=1;}s=s_;}void PULSE::Set(bool s_){if(s_==1&&s==0){tt=0;nc=0;ms2=microPLC::ms;on=1;q=1;}s=s_;if(s_==0){q=0;on=0;}}void PULSE::TOff(int toff_){if(toff_)toff=toff_;else toff=1;}void PULSE::N(int n_){n=n_;}bool PULSE::Q(void){timer();return q;}unsigned int PULSE::getN(void){return nc;}void PULSE::timer(void){if(on){timerAVR();if(q){if(tt>=t*tb){q=0;tt=0;}}else{if(tt>=toff*tb){q=1;tt=0;nc++;if(n!=0){if(nc>=n){q=0;on=0;}}}}}}microPLC MICROPLC;