工控数字输入,定时器,计数器,代码库
plc.h
typedef struct{
unsigned char coil:1;
unsigned char contact:1;
unsigned int acc;
unsigned int set;
}TIME_RELAY;
typedef struct{
unsigned char coil:1;
unsigned char coil_old:1;
unsigned char contact:1;
unsigned char overflow:1;
unsigned int acc;
unsigned int set;
}COUNTER;
typedef struct {
unsigned char in:1;
unsigned char out:1;
unsigned char out_old:1;
unsigned char rise:1;
unsigned char fall:1;
unsigned char high_acc:8;
unsigned char low_acc:8;
unsigned char confirm_time;
}DI_FILTER;
void init_time_relay(TIME_RELAY *time_relay);
void scan_time_relay(TIME_RELAY *time_relay);
void init_counter(COUNTER *cu);
void scan_counter(COUNTER *cu);
void init_digital_input(DI_FILTER *di);
void scan_digital_input(DI_FILTER *di);
void init_plc(void);
void scan_plc(void);
unsigned char is_fall(unsigned char new,unsigned char *old);
unsigned char is_rise(unsigned char new,unsigned char *old);
plc.c
#ifndef __PLC__H__
#include "plc.h"
#define __PLC__H__
#endif
TIME_RELAY T[16];
COUNTER C[16];
DI_FILTER DI[16];
void init_time_relay(TIME_RELAY *time_relay)
{
time_relay->coil=0;
time_relay->contact=0;
time_relay->acc=0;
time_relay->set=100;
}
void scan_time_relay(TIME_RELAY *time_relay)
{
if(time_relay->coil)
{
time_relay->acc++;
if(time_relay->acc>time_relay->set) time_relay->contact=1;
}
else
{
time_relay->acc=0;
time_relay->contact=0;
}
}
void init_counter(COUNTER *cu)
{
cu->coil=0;
cu->coil_old=1;
cu->contact=0;
cu->acc=0;
cu->set=0;
}
//上升沿计数器
void scan_counter_ctu(COUNTER *cu)
{
if(cu->coil==1 && cu->coil_old==0) cu->acc++;
cu->coil_old=cu->coil;
if(cu->acc>cu->set) cu->contact=1;
}
//下降沿计数器
void scan_counter_ctd(COUNTER *cu)
{
if(cu->coil==0 && cu->coil_old==1) cu->acc++;
cu->coil_old=cu->coil;
if(cu->acc>cu->set) cu->contact=1;
}
void init_digital_input(DI_FILTER *di)
{
di->in=0;
di->out=0;
di->high_acc=0;
di->low_acc=0;
di->out_old=0;
di->confirm_time=10;
}
void scan_digital_input(DI_FILTER *di)
{
if(di->in)
{
di->high_acc++;
if(di->high_acc>di->confirm_time) di->out=1;
di->low_acc=0;
}
else
{
di->low_acc++;
if(di->low_acc>di->confirm_time) di->out=0;
di->high_acc=0;
}
di->rise=(di->out_old==0 && di->out==1);
di->fall=(di->out_old==1 && di->out==0);
di->out_old=di->out;
}
void init_plc(void)
{
unsigned char j=0;
for(j=0;j<16;j++) {
init_time_relay(&T[j]);
init_counter(&C[j]);
init_digital_input(&DI[j]);
}
}
void scan_plc(void)
{
unsigned char j=0;
for(j=0;j<16;j++) {
scan_time_relay(&T[j]);
}
for(j=0;j<4;j++) {
scan_counter_ctu(&C[j]);
}
for(j=4;j<8;j++) {
scan_counter_ctd(&C[j]);
}
for(j=0;j<7;j++) {
scan_digital_input(&DI[j]);
}
}
|
要全部掌握真不容易
太棒了