飞思卡尔光电组程序

合集下载

飞思卡尔单片机LED控制例程详解-推荐下载

飞思卡尔单片机LED控制例程详解-推荐下载
我的第一个 LED 程序
准备工作: 硬件:Freescale MC9S08JM60 型单片机一块; 软件:集成开发环境 codewarrior IDE; 开发板上有两个 LED 灯,如下图所示:
实验步骤: 1. 首先,确保单片机集成开发环境及 USBDM 驱动正确安装。其中 USBDM 的安装步骤如下: 假设之前安装过单片机的集成开发环境 6.3 版本:CW_MCU_V6_3_SE; 运行 USBDM_4_7_0i_Win,这个程序会在 c 盘的程序文件夹下增加一个目录 C:\Program
对全部高中资料试卷电气设备,在安装过程中以及安装结束后进行高中资料试卷调整试验;通电检查所有设备高中资料电试力卷保相护互装作置用调与试相技互术通关,1系电过,力管根保线据护敷生高设产中技工资术艺料0不高试仅中卷可资配以料置解试技决卷术吊要是顶求指层,机配对组置电在不气进规设行范备继高进电中行保资空护料载高试与中卷带资问负料题荷试2下卷2,高总而中体且资配可料置保试时障卷,各调需类控要管试在路验最习;大题对限到设度位备内。进来在行确管调保路整机敷使组设其高过在中程正资1常料中工试,况卷要下安加与全强过,看度并22工且22作尽22下可22都能22可地护以缩1关正小于常故管工障路作高高;中中对资资于料料继试试电卷卷保破连护坏接进范管行围口整,处核或理对者高定对中值某资,些料审异试核常卷与高弯校中扁对资度图料固纸试定,卷盒编工位写况置复进.杂行保设自护备动层与处防装理腐置,跨高尤接中其地资要线料避弯试免曲卷错半调误径试高标方中高案资等,料,编试要5写、卷求重电保技要气护术设设装交备备置底4高调、动。中试电作管资高气,线料中课并敷3试资件且、设卷料中拒管技试试调绝路术验卷试动敷中方技作设包案术,技含以来术线及避槽系免、统不管启必架动要等方高多案中项;资方对料式整试,套卷为启突解动然决过停高程机中中。语高因文中此电资,气料电课试力件卷高中电中管气资壁设料薄备试、进卷接行保口调护不试装严工置等作调问并试题且技,进术合行,理过要利关求用运电管行力线高保敷中护设资装技料置术试做。卷到线技准缆术确敷指灵设导活原。。则对对:于于在调差分试动线过保盒程护处中装,高置当中高不资中同料资电试料压卷试回技卷路术调交问试叉题技时,术,作是应为指采调发用试电金人机属员一隔,变板需压进要器行在组隔事在开前发处掌生理握内;图部同纸故一资障线料时槽、,内设需,备要强制进电造行回厂外路家部须出电同具源时高高切中中断资资习料料题试试电卷卷源试切,验除线报从缆告而敷与采设相用完关高毕技中,术资要资料进料试行,卷检并主查且要和了保检解护测现装处场置理设。备高中资料试卷布置情况与有关高中资料试卷电气系统接线等情况,然后根据规范与规程规定,制定设备调试高中资料试卷方案。

飞思卡尔智能车 智能车源代码光电组(有注解)

飞思卡尔智能车 智能车源代码光电组(有注解)

智能车源代码光电组(有注解)#include <hidef.h> /* common defines and macros */#include <mc9s12dg256.h> /* derivative information */#include "math.h"#include "PWM.h"#include "A TD.h"#include "LQprintp.h"#pragma LINK_INFO DERIV A TIVE "mc9s12dg256b"unsigned int i = 0;unsigned int j = 0;unsigned int t = 0;byte ad_value[13];uchar data[13];int sum = 0;uchar start_flag = 0;uchar num = 0;uchar lw=0;unsigned int per = 65530;int SPWM = 0;int L_SPWM = 0;unsigned int SPmax = 1000;int MPWM = 0;uchar current_corrd = 0;static unsigned int mem_num = 0;//***********************PID**************** ***************static unsigned int Kp=25;static unsigned int Kp2=60;static unsigned int Ki=9;static unsigned int Kd=30;static unsigned int rKp=100;static unsigned int rKp2=60;static unsigned int rKi=0;static unsigned int rKd=60;unsigned short E = 5;unsigned char q = 1;int Mp = 0;int Mi = 0;int Md = 0;int Mp2 = 0;int P_Speed = 0;int L_u[3];//****************************************** ****************//***********************舵机PID变量**********************static unsigned int s_sKp=35; //直道PID的P值static unsigned int s_sKp2=0; //直道PID 的二阶P值static unsigned int s_sKi=0; //直道PID的I值static unsigned int s_sKd=10; //直道PID的D值//****用于防止PID溢出******unsigned short s_sE = 5;unsigned char s_sq = 1;//*************************//****分别存放P I D 值*****int s_sMp = 0;int s_sMi = 0;int s_sMd = 0;int s_sMp2 = 0;//*************************int sL_u[3]; //存放前3次理论速度与实际速度的差值int last_corrd[3][10] ={{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}};//****************************************** ***************//*********************PID调试中断**************************unsigned char cp = 0;unsigned char ci = 0;unsigned char cd = 0;unsigned int search_PACN10;unsigned int np = 0;unsigned int sp[500];//****************************************** ****************//*********************存储前20点的数据*********************int L_num[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};int sum_corrd = 0;int wb = 0; //记录当前状态黑为0,白为1;//****************************************** ****************//********************红外滤波*****************************int corrd[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};int T_corrd = 0;int is_white = 0;int numb = 0;//****************************************** ****************//***********************数据统计***************************int corrd_sate[23] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};int SPWM_sate[15] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};int MPWM_sate[11] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; uchar corrd_time[512];uchar SPWM_time[512];uchar MPWM_time[512];uchar PACN_time[512];//****************************************** ****************void setbusclock(void){CLKSEL=0X00; //disengage PLL to systemPLLCTL_PLLON=1; //turn on PLL SYNR=1;REFDV=1;//pllclock=2*osc*(1+SYNR)/(1+REFDV)=32MHz;_asm(nop); //BUS CLOCK=16M_asm(nop);while(!(CRGFLG_LOCK==1)); //when pll is steady ,then use it;CLKSEL_PLLSEL =1; //engage PLL to system;}void Dly_ms(int ms){int ii,jj;if (ms<1) ms=1;for(ii=0;ii<ms;ii++)for(jj=0;jj<2670;jj++);//busclk:16MHz--1ms}static void SCI_Init(void){SCI0CR2=0x2c; //enable Receive Full Interrupt,RX enable,Tx enableSCI0BDH=0x00; //出口波特率为9600SCI0BDL=0x68;//SCI0BDL=busclk/(16*SCI0BDL)//busclk 8MHz, 9600bps,SCI0BDL=0x34//busclk 16MHz, 9600bps,SCI0BDL=0x68//busclk 24MHz, 9600bps,SCI0BDL=0x9C} //busclk 32MHz, 9600bps,SCI0BDL=0xD0static void IOC_Init(void){ PERT = 0XFF;//PPST=0XFF;DDRT=0XFe;PBCTL=0X50;//PT0 PIN,PACN10 16BIT,FALLing edge,NOT INTERRUPT//PACN0=200;//PACN1=0xFF;TCTL4=0x01;//40表示ICx禁止, 1表示上升沿, 2表示下降沿, 3表示任何沿//TIE =0x00;//每一位对应相应通道中断允许,0表示禁止中断TIOS =0xfe;//每一位对应通道的: 0输入捕捉,1输出比较}unsigned int get_Speed(){int Speed;Speed = PACN10;PACN10 = 0;return Speed;}void s_PID_MPWM(){L_u[2] = L_u[1];L_u[1] = L_u[0];L_u[0] = P_Speed - search_PACN10;Mp = Kp * L_u[0];Mi = Mi + Ki * L_u[0];Md = Kd * (L_u[0] - 2 * L_u[1] + L_u[2]);Mp2 = Kp2 * (L_u[0] - L_u[1]);if(((Ki * L_u[0]) > E)||((Ki * L_u[0]) < -E)) q = 0; else q = 1;MPWM = MPWM + Mp + q * Mi + Md + Mp2;if(MPWM > 1000) MPWM = 1000;if(MPWM < -1000) MPWM = -1000;Set_MPWM(MPWM);}void r_PID_MPWM(){L_u[2] = L_u[1];L_u[1] = L_u[0];L_u[0] = P_Speed - search_PACN10;Mp = rKp * L_u[0];Mi = Mi + rKi * L_u[0];Md = rKd * (L_u[0] - 2 * L_u[1] + L_u[2]);Mp2 = rKp2 * (L_u[0] - L_u[1]);if(((rKi * L_u[0]) > E)||((rKi * L_u[0]) < -E)) q = 0; else q = 1;MPWM = MPWM + Mp + q * Mi + Md + Mp2;if(MPWM > 1000) MPWM = 1000;if(MPWM < -1000) MPWM = -1000;Set_MPWM(MPWM);}//*******************舵机PID控制函数*************************void s_PID_SPWM(){sL_u[2] = sL_u[1];sL_u[1] = sL_u[0];sL_u[0] = ((current_corrd+last_corrd[0][1]) - (last_corrd[0][2]+last_corrd[0][3]))/2;//*********计算PID值***********if(sL_u[0]<20 && sL_u[0]>-20){s_sMp = s_sKp * sL_u[0];s_sMi = s_sMi + s_sKi * sL_u[0];s_sMd = s_sKd * (sL_u[0] - 2 * sL_u[1] + sL_u[2]);s_sMp2 = s_sKp2 * (sL_u[0] - sL_u[1]);//*****************************//***********I项溢出防止*******if(((s_sKi * sL_u[0]) > s_sE)||((s_sKi * sL_u[0]) < -s_sE)) s_sq = 0;else s_sq = 1;//*****************************SPWM = SPWM + s_sMp + s_sq * s_sMi + s_sMd + s_sMp2;//*********PWM溢出防止*********if(SPWM > 70) SPWM = 70;if(SPWM < -70) SPWM = -70;//*****************************}else sL_u[0] = sL_u[1];Set_SPWM(SPWM);}//****************************************** ****************void show_SPWM_data(){for(j = 0; j < 15; j++){printp("%10d", SPWM_sate[j]);}}void show_MPWM_data(){for(j = 0; j < 11; j++){printp("%10d", MPWM_sate[j]);}}void show_corrd_data(){for(j = 0; j < 23; j++){printp("%6d", corrd_sate[j]);}}void show_corrd_time(){for(j = 0; j < 512; j++){printp("%c", corrd_time[j]);}}void show_SPWM_time(){for(j = 0; j < 512; j++){printp("%c", SPWM_time[j]);}}void show_MPWM_time(){for(j = 0; j < 512; j++){printp("%c", MPWM_time[j]);}}void show_PACN_time(){for(j = 0; j < 512; j++){printp("%c", PACN_time[j]);}}void main(void) {/* put your own code here */setbusclock();SCI_Init();AD_Init();IOC_Init();Ini_PWM();EnableInterrupts;for(;;){Dly_ms(10);//*************红外滤波*************************for(j=0; j<10; j++){adc_get(ad_value);for(i = 1; i<12; i++){if(ad_value[i]>=160){data[i] = 1;num = num + 1;}else data[i] = 0;sum = sum + data[i] * 2*i;//printp("%10d", data[i]);}if(num == 0){corrd[j] = -1;}else{corrd[j] = sum/num;}sum = 0;num = 0;}is_white = 0;for(i=0;i<10;i++){if(corrd[i] < 0){is_white++;}for(j=i;j<10;j++){T_corrd = corrd[j];corrd[j] = corrd[i];corrd[i] = T_corrd;}}if(is_white > 6){numb = 0;}sum = 0;j = 0;for(i=3; i<8; i++){if(corrd[i] > -1){sum += corrd[i];j++;}}if(j!=0){current_corrd = sum/j;numb = j;}L_num[9] = L_num[8];L_num[8] = L_num[7];L_num[7] = L_num[6];L_num[6] = L_num[5];L_num[5] = L_num[4];L_num[4] = L_num[3];L_num[3] = L_num[2];L_num[2] = L_num[1];L_num[1] = L_num[0];L_num[0] = numb;//****************************************************wb = L_num[1]|L_num[2]|L_num[3]|L_num[4]|L_num[5]| L_num[6]|L_num[7]|L_num[8]|L_num[9];if(numb == 0){DDRB = 0x80;if(search_PACN10 > 10 && wb>0){P_Speed = 20;if(lw == 0){SPWM = -70;}else{SPWM = 72;}//if(sum_corrd<220&&sum_corrd>-220)Set_MPWM(0);// else// Set_MPWM(700);}else{P_Speed = 20;if(lw == 0){SPWM = -70;}else{SPWM = 72;}Set_MPWM(1000);}//Set_MPWM(0);}else{DDRB = 0x00;// printp("%d ", current_corrd);// if(PTJ & 0x80) Set_MPWM(0);//elseif(wb == 0){Set_MPWM(1000);}else{switch(current_corrd){case 2: SPWM = -70;P_Speed = 32;r_PID_MPWM();lw = 0;break;case 3: SPWM = -60;P_Speed = 32;r_PID_MPWM();lw = 0;break;case 4: SPWM = -50;P_Speed = 32;r_PID_MPWM();lw = 0;break;case 5: SPWM = -40;P_Speed =32;r_PID_MPWM();lw = 0;break;case 6: SPWM = -30;P_Speed = 32;r_PID_MPWM();lw = 0;break;case 7: SPWM = -25;P_Speed = 32;r_PID_MPWM();lw = 0;break;case 8: SPWM = -20;P_Speed = 32;r_PID_MPWM();lw = 0;break;case 9: SPWM = -15;P_Speed = 32;s_PID_MPWM();lw = 0;break;case 10: SPWM = -10; P_Speed = 32;s_PID_MPWM();lw = 0;break;case 11: SPWM = -5; P_Speed = 32;s_PID_MPWM();lw = 0;break;case 12: SPWM = 0; P_Speed = 32;s_PID_MPWM();break;case 13: SPWM = 5; P_Speed = 32;s_PID_MPWM();lw = 1;break;case 14: SPWM = 10; P_Speed = 32;s_PID_MPWM();lw = 1;break;case 15: SPWM = 15; P_Speed = 32;s_PID_MPWM();lw = 1;break;case 16: SPWM = 20; P_Speed = 32;r_PID_MPWM();lw = 1;break;case 17: SPWM = 25; P_Speed = 32;r_PID_MPWM();lw = 1;break;case 18: SPWM = 30; P_Speed = 32;r_PID_MPWM();lw = 1;break;case 19: SPWM = 40; P_Speed = 32;r_PID_MPWM();lw = 1;break;case 20: SPWM = 50; P_Speed = 32;r_PID_MPWM();lw = 1;break;case 21: SPWM = 60; P_Speed = 32;r_PID_MPWM();lw = 1;break;case 22: SPWM = 70; P_Speed = 32;r_PID_MPWM();lw = 1;break;default: break;}//Set_MPWM(500);}}last_corrd[0][3] = last_corrd[0][2];last_corrd[0][2] = last_corrd[0][1];last_corrd[0][1] = last_corrd[0][0];last_corrd[0][0] = current_corrd;corrd_sate[current_corrd]++;SPWM_sate[SPWM/10+7]++;MPWM_sate[MPWM/10]++;corrd_time[t]=current_corrd;SPWM_time[t]=SPWM+70;MPWM_time[t]=(MPWM+1000)/10;s_PID_SPWM();//Set_SPWM(SPWM);//Set_MPWM(500);search_PACN10 = PACN10;//printp("%10d", search_PACN10);PACN_time[t]=search_PACN10;PACN10 = 0;sum_corrd = 0;sum = 0;start_flag = 0;num = 0;t++;if(t==512){MPWM=0;for(;;);}} /* wait forever *//* please make sure that you never leave this function */}void interrupt 20 SCI0RX(void) {byte result,temp;DisableInterrupts;temp=SCI0SR1; /*clear flag*/result=SCI0DRL;if(result=='s'||result=='S') show_SPWM_data();if(result=='M'||result=='m') show_MPWM_data(); if(result=='c'||result=='C') show_corrd_data();if(result=='1'||result=='!') show_corrd_time();if(result=='2'||result=='@') show_SPWM_time();if(result=='3'||result=='#') show_MPWM_time();if(result=='4'||result=='$') show_PACN_time();if(result=='a'||result=='A'){MPWM=0;for(;;)EnableInterrupts;;}EnableInterrupts;}。

飞思卡尔程序

飞思卡尔程序

飞思卡尔程序#include <hidef.h> /* common defines andmacros */#include <mc9s12dg128.h> /* derivativeinformation *///#include "PWM.h"//#include "AD.h"#include "control.h"#pragma LINK_INFO DERIVATIVE "mc9s12dg128b"word AD_wData[9]; //全局变量存放 AD0,AD1,AD2的结果word sum[9]; //初始化时为求平均值,全白中,各个灯的FF次的电压和word avrg0[9]; //全白时各个灯的平均电压word summ[9];//初始化时为求平均值,全黑中,各个灯的FF次的电压和word avrg1[9]; //全黑时各个灯的平均电压word ss[9]; //实际采集来的各个灯的电压word s[9]; // 实际采集来的各个灯的电压word sum2[8];//用于存放两两灯电压之和word k; //用于存放比较出的最大值uint h=1500;//转角大小int flag = 0;//标志中间灯是否第一次在黑道附近int flagg=0;//标志0灯从哪边感应到黑道int flagg1=0;//标志8灯从哪边感应到黑道int flagg0=0;//标志是左边还是右边出道int j=0;dword i;dword m;dword s0;dword s1;dword p11=0;//以下四个变量用于记录黑道处于同一侧的时间dword p12=0;dword p21=0;dword p22=0;word max0[9]=0;//初始化时采集来的黑道的值int g=0;//为过滤算法使用word cha[9];//用来存放黑白电压差int ffgg0=0;//标志是否用中间板采的数据int ffgg1=0;//标志是否用中间板采的数据word sum0=0; //初始化时采集来9个灯的全白电压和//word sum1=0; //实际采集来的左4个灯的电压和//word sum22=0; //实际采集来的右4个灯的电压和int fla=0;//标志是出道还是入道void AD_Init();void PWM_Init();void PWM_Init1();//void PID();void AD_Init(void) //AD初始化{//控制寄存器2:上电,标志位快速清零,开中断ATD0CTL2 =(ATD0CTL2_ADPU_MASK|ATD0CTL2_AFFC_MASK|ATD0CTL2_ASCIE_MASK) ;ATD1CTL2 =(ATD1CTL2_ADPU_MASK|ATD1CTL2_AFFC_MASK|ATD1CTL2_ASCIE_MASK) ;//控制寄存器3:转换序列长度为3ATD0CTL3 =0x78;//(ATD0CTL3_S2C_MASK|ATD0CTL3_S1C_MASK);ATD1CTL3 =0x78;//(ATD1CTL3_S2C_MASK|ATD1CTL3_S1C_MASK);//控制寄存器4:ATD0CTL4 =(ATD0CTL4_SRES8_MASK|ATD0CTL4_PRS1_MASK|ATD0CTL4_PRS0_MASK) ;ATD1CTL4 =(ATD1CTL4_SRES8_MASK|ATD1CTL4_PRS1_MASK|ATD1CTL4_PRS0_MASK) ;//控制寄存器5:ATD0CTL5 =(ATD0CTL5_DJM_MASK|ATD0CTL5_SCAN_MASK|ATD0CTL5_MULT_MASK);ATD1CTL5 =(ATD1CTL5_DJM_MASK|ATD1CTL5_SCAN_MASK|ATD1CTL5_MULT_MASK); ATD0DIEN=0x00; // 禁止数字输入缓冲ATD1DIEN=0x00; // 禁止数字输入缓冲}#pragma CODE_SEG NON_BANKED //中断服务程序#pragma TRAP_PROCvoid interrupt 22 Int_AD0(void){AD_wData[0] = ATD0DR0; //将结果寄存器中的值存放到数组中AD_wData[1] = ATD0DR1; //将结果寄存器中的值存放到数组中AD_wData[2] = ATD0DR2; //将结果寄存器中的值存放到数组中AD_wData[3] = ATD0DR3;AD_wData[4] = ATD0DR4;AD_wData[5] = ATD0DR5;AD_wData[6] = ATD0DR6;AD_wData[7] = ATD0DR7;AD_wData[8] = ATD1DR0;}#pragma CODE_SEG DEFAULTword max(word a,word b,word c,word d,word e,wordf,word r,word w) {word maxx=0;if(a>maxx)maxx=a;if(b>maxx)maxx=b;if(c>maxx)maxx=c;if(d>maxx)maxx=d;if(e>maxx)maxx=e;if(f>maxx)maxx=f;if(r>maxx)maxx=r;if(w>maxx)maxx=w;return maxx;}void delay0(){for(i=0;i<0xFFFF;i++)for(m=0;m<0x05;m++);}void delay1(){for(i=0;i<0xFFFF;i++);// for(i=0;i<0xFFFF;i++);}void main(void){AD_Init(); //AD 初始化DDRB = 0xFF;DDRA_BIT6=0; //A_BIT6口作为第二块板左边传感器的输入口 DDRA_BIT7=0; //A_BIT7口作为第二块板右边传感器的输入口 PORTB = 0xFF;p=0;for(j=0;j<9;j++){AD_wData[j] = 0; //全局变量初始化sum[j]=0;avrg0[j]=0;avrg1[j]=0;summ[j]=0;}for(j=0;j<9;j++) {max0[j]=0;ss[j]=0;}for(j=0;j<8;j++)sum2[j]=0;EnableInterrupts; //开AD中断for(i=0;i<0xFFFF;i++);for(i=0;i<0xFF;i++) //只能是FF,防止下面sum溢出 {for(j=0;j<9;j++)//采集白道路信息{sum[j]=sum[j]+AD_wData[j];}}for(i=0;i<9;i++) {sum0=sum0+sum[i]/0xFF;avrg0[i]=sum[i]/0xFF;}PORTB=sum[0]/0xFF; //显示0通道采集到的值delay0();PORTB=0x00;//显示马上得进行黑道信息采集了delay1();for(j=0;j<9;j++){for(m=0;m<0xFF;m++){summ[j]=summ[j]+AD_wData[j];}avrg1[j]=summ[j]/0xFF;PORTB=avrg1[j]; //显示采来的黑道信息cha[j]=avrg1[j]-avrg0[j];delay0();PORTB=0x00; //显示马上得进行下一次黑道信息采集了 delay1();}PORTB=0x00;//灯全亮,提示车马上就可以跑了delay1();PWM_Init() ;PWM_Init1(1500,1,200);for(i=0;i<0xFFF;i++);// delay1();for(;;){int f=0;u3=100;if(flagk1==1){p21=0;flagk2=0;p11++;if(p11==0xFFF)flagkk1=1;}else if(flagk2==1){p11=0;flagk1=0;p21++;if(p21==0xFFF)flagkk2=1;}for(f=0;f<9;f++){s[f]=AD_wData[f];ss[f]=s[f]-(avrg0[f]-0x50); //当前值减去初始白道值,以便比较}for(f=0;f<8;f++)sum2[f]=ss[f]+ss[f+1]; //两两灯电压之和//减去1.6V防止溢出*******************if(AD_wData[0]<0xC0&& AD_wData[1]<0xC0&&AD_wData[2]<0xC0&&AD_wData[3]<0xC0&&AD_wData[4]<0xC0&&AD_wData[5]<0xC0&&AD_wData[6]<0xC0&&AD_wD ata[7]<0xC0&&AD_wData[8]<0xC0){if(sum2[0]<0xC0&&sum2[1]<0xC0&&sum2[2]<0xC0&&sum2[3]<0xC0&&sum2[4]<0xC0&&sum2[5]<0xC0&&sum2[6]<0xC0&&sum2[7]<0xD0){fla=1;if(flagg0==1){for(i=0;i<0xFF;i++);PWM_Init1(1140,u1,200);flagk1=1;flagkk2=0;for(;;){if(AD_wData[4]>0xB0||AD_wData[5]>0xB0||AD_wData[6]>0xB0|| AD_wData[7]>0xB0||AD_wData[8]>0xB0){flagg0=0;break;}}}else if(flagg0==2){for(i=0;i<0xFF;i++);PWM_Init1(1860,u1,200);flagk1=0;flagkk2=1;for(;;)if(AD_wData[0]>0xB0||AD_wData[1]>0xB0||AD_wData[2]>0xB0||AD_wData[3]>0xB0||AD_wData[4]>0xB0){flagg0=0;break;}}}else{}}else{if(s[0]-(avrg0[0]-0x13)<0x40 &&s[1]-(avrg0[1]-0x13)<0x40 &&s[2]-(avrg0[2]-0x13)<0x40 && s[3]-(avrg0[3]-0x13)<0x40 &&s[4]-(avrg0[4]-0x13)<0x40 && s[5]-(avrg0[5]-0x13)<0x40 &&s[6]-(avrg0[6]-0x13)<0x40 && s[7]-(avrg0[7]-0x13)<0x40 &&s[8]-(avrg0[8]-0x13)<0x40)///////////注意调整该值36***************{/* if(PORTA_BIT6!=0||PORTA_BIT7!=0){if(PORTA_BIT6!=0&&PORTA_BIT7==0)PWM_Init1(1900,200,1);else if(PORTA_BIT7!=0&&PORTA_BIT6==0)PWM_Init1(1100,200,1);}*/}else{k=max(sum2[0],sum2[1],sum2[2],sum2[3],sum2[4],sum2[5],sum2[ 6],sum2[7]);//谁两和最大,黑道就在谁两之间if(k==sum2[0]){p=0;flagg0=2;if(fla==1)control_11();else if(fla==0) control_1();}else{if(k==sum2[1]){p=0;p1=0;fla=0;control_2(s[1],s[2],ss[1],ss[2],cha[1],cha[2],avrg0[1],avrg 0[2]);}else{if(k==sum2[2]){p=0;p1=0;fla=0;control_3(s[2],s[3],ss[2],ss[3],cha[2],cha[3],avrg0[2],avrg 0[3]);}else{if(k==sum2[3]){p=0;p1=0;fla=0;control_4(s[3],s[4],ss[3],ss[4],cha[3],cha[4],avrg0[3],avrg 0[4]);}else{if(k==sum2[4]){fla=0;p1=0;control_5(s[4],s[5],ss[4],ss[5],cha[4],cha[5],avrg0[4],avrg 0[5]);}else{if(k==sum2[5]){fla=0;p1=0;control_6(s[5],s[6],ss[5],ss[6],cha[5],cha[6],avrg0[5],avrg 0[6]);}else{if(k==sum2[6]){p=0;p1=0;fla=0;control_7(s[6],s[7],ss[6],ss[7],cha[6],cha[7],avrg0[6],avrg 0[7]);}else{if(k==sum2[7]){p=0;flagg0=1;if(fla==0)control_8(); elseif(fla==1)control_88(); } else{}}}}}}}}}}}}。

飞思卡尔 摄像头 程序

飞思卡尔  摄像头  程序

}
/*************************************************************/
/* 行场中断初始化函数 */
/*************************************************************/
#include <hidef.h>
#include "derivative.h"
#include <mc9s12xs128.h>
#define ROW 40 //数字摄像头所采集的二维数组行数
#define COLUMN 120 //数字摄像头所采集的二维数组列数
PLLCTL_PLLON=1; //turn on PLL
SYNR =0xc0 | 0x09;
REFDV=0x80 | 0x01;
POSTDIV=0x00; //pllclock=2*osc*(1+SYNR)/(1+REFDV)=160MHz;
#define ROW_START 10 //数字摄像头二维数组行开始行值
#define ROW_MAX 200 //数字摄像头所采集的二维数组行最大值
#define THRESHOLD 0x68 //图像阈值,根据所采集图像亮度值大小的实际情况调整(OV7620所采集的亮度值大小为0--255)
/*************************************************************/
void main(void)
{
/* put your own code here */

飞思卡尔摄像头组智能车程序代码

飞思卡尔摄像头组智能车程序代码

//---------------------------------------------------CCD#define odd_even PTIT_PTIT3#define ROW_START 30 // begin to sample from line start#define ROW_END 240 // end flag of samplingunsigned char frm,open_frm,flag1,finish=0;#define ROW_MAX 12 //最大取12行#define LINE_MAX 52unsigned char image_data[ROW_MAX][LINE_MAX];//unsigned char image_simple[10]; /////////装10个黑点,只处理10个//char row,line;char row;unsigned int line;unsigned char temp;unsigned int rowcount;unsigned char line_temp;//-------------------------------------------CCD_PROCESS#define RMV_ROW 2 //抛弃前2行0-4行#define V ALVE 24 // valve to decide black track or white trackunsigned char black_x[ROW_MAX];#define Abso_Center 25 //中心位置22unsigned int cigma,curve;unsigned int Curve_lev2=45;//大弯区分S直与曲线,直和S应该很小unsigned int Curve_lev1=24;//小弯valve to decide straight track or notunsigned char average,Relative_Poz;unsigned int sum;char r_HEAD;unsigned char flag_fail=0,flag_BigCurv=0,flag_Straight=0,flag_Curv=0; //char head;unsigned char flag_black_x_normal;#define normal_black_x 6 //need for adjust ,may need be larger,used for tell cross/start_line/ring from miss_line//--------------------------------------------PWM CONTROL#define PWM_MID 2813//2813 //mid//#define PWM_RIGHT 3750 //right#define PWM_RIGHT 3500//3600//#define PWM_LEFT 1875 //left#define PWM_LEFT 2200int speed,lastspeed;int steer,laststeer;int rev_speed,last_rev_speed;int speed_e,lastspeed_e;int rev_speed_e,last_rev_speed_e;//#define high_speed 250 // speed used on straight trackint speed_MAX;int speed_set_curve;//#define low_speed 100 // speed used on the turnunsigned char stand;//unsigned int speed_vari;unsigned char K_speed=1,K_steer=1;//-------------------------------------------OTHER V ARunsigned char a,b,c,x;char m,n,i,j,s;//unsigned char Start_Flag=0,Circle=0,Circle_Count=2,BEGIN=0,STOP=0;//探测起跑线,一圈停车unsigned char start_count;unsigned char flag_start,flag_stop,flag_heap;#define circle 2 //run 2 circlevoid IRQ_ISR(void);void RTI_ISR(void);int pa_count;int speed_set,rev_speed_set;int Kp=20,Kd=3;#include <hidef.h>#include <MC9S12XS128.h>#include "includes.h"#pragma LINK_INFO DERIV ATIVE "mc9s12xs128"//--------------------------------------------------------------------------------------//------initial----------initial---------------initial------------------initial------//-----------------------------------------------------------------------------------void init_PLL(void) //CPU总线时钟60M{REFDV=0x43;SYNR=0xce;POSTDIV=0x00; //bus period=16Mhz*(SYNR+1)/(REFDV+1)=60Mwhile(0==CRGFLG_LOCK); //wait for VCO to stablizeCLKSEL=0x80; //open PLL}void init_PORT(void) //端口初始化{DDRT_DDRT3=0; //PT3作为奇偶场信号输入DDRT_DDRT1=0; //PT1作为测速信号输入//DDRJ_DDRJ6=1; //控制电机使能,输出IRQCR=0xc0; //外部IRQ使能,行同步,下降沿//IRQCR_IRQE=1;//IRQCR_IRQEN=1;DDRA=0x00; //A口作为速度调试输入DDRB=0xff;PORTB=0x01;}void init_PWM(void){PWME=0x00; //pwm disablePWMPOL=0xff; //输出开场为高电平, 当给定计数到来时变低电平PWMCLK=0x00; //PWM0,1--A; PWM2,3--B; PWM4,5--A;PWMPRCLK=0x55; //A=B=60M/32=PWMCAE=0x00; //对齐方式:左对齐PWMCTL_CON01=1; //PWM01 合并16 bitPWMPER01=375; //PWM1 Period=375/=0.2ms.f=5kHZPWMDTY01=258; //PWME_PWME1 = 1; //电机enablePWMCTL_CON23=1; //PWM23 合并16 bitPWMPER23=375; //PWM3 Period=37500/=20ms,f=50HZPWMDTY23=0; // the duty cycle is 2813/37500=7.5%PWME_PWME3=1; // 舵机enablePWMCTL_CON45=1; //PWM45 合并16 bitPWMPER45=37500; //PWM5 Period=1875/=1ms.f=5kHZPWMDTY45=PWM_MID; //PWME_PWME5=1; //电机enable}void init_ECT(void) //定时器初始化??{TIOS=0; //通道0-7作为输入TCNT=0x00; //计数器清零TSCR1=0x80; //计数器使能TCTL4=0x07; //设置通道0捕获上、下沿,通道1捕获上沿PACTL=0X50; //PA使能,上升沿}void init_AD(void){ATD0CTL1=0x00; //External trigge source is AN0,8-bit data,No discharge before sampling ATD0CTL2=0x60; //quick clear CCFx,contine to transform under wait mode,Disable external trigger,ATD Sequence Complete interrupt requests are disabled,A TD Compare interrupt requests are disabledATD0CTL3=0x88; //one transform in one sequence, No FIFO,Right justied,contine to transform under freeze modeATD0CTL4=0x01; //four clocks,ATDCLK=[BusClock*0.5]/[PRS+1]=15MATD0CTL5=0x20; //Continuous Conversion Sequence Mode,Analog Input Channel is AN0 ATD0DIEN=0x00; //inhibit digital input//-------------------------------------------------------------------------------------//rti realtime interrut initial//--- 120-7 130-8 ..... 160-11 230-18 300-23// 100-9//------------------static void RTI_Init(void){RTICTL=0xff; // 8* 2(16) scale 32.75(16M)CRGINT=0x80; //enable}//------//------------------------------------------------------------------------------------------------//----functions---------------functions-----------functions--------functions---------functions-------------------------------------------//------------------------------------------------------------------------------------------------unsigned int abs_sub(unsigned int num1, unsigned int num2){ unsigned int difference;if(num1>=num2){difference=num1-num2;}else{difference=num2-num1;}return difference;}//--------//delay//--------void delay(int Dly_time){for(i=0;i<Dly_time;i++);}//-----------------------------------------------------------------------------------//- 滤波//---------------------------------------------------------------------------------------unsigned char get_mid(unsigned char a,unsigned char b,unsigned char c){unsigned char x=0;if(a>b) {x=b;b=a;a=x;}if(b>c) {x=c;c=b;b=x;}if(a>c) {x=c;c=a;a=x;}return b;}//-------------------------------------------------------// jump_count//-------------------------------------------------------unsigned char jump_6(unsigned char Row){unsigned int i1,i2,i3,i4,i5;unsigned char flag_6jump=0;for(i1=LINE_MAX-1;i1>=10;i1--){ //for i1if(image_data[Row][i1-2]+V ALVE<image_data[Row][i1]){//if find right blcak_x ,jump1 ,i2 no1 blackfor(i2=i1-3;i2>=8;i2--){if(image_data[Row][i2]+V ALVE<image_data[Row][i2-2]){// jump2 i3 no2 whitefor(i3=i2-2;i3>=10;i3--){if(image_data[Row][i3-2]+V ALVE<image_data[Row][i3]){// jump3 i4 no3 blackfor(i4=i3-2;i4>=8;i4--){if(image_data[Row][i4]+V ALVE<image_data[Row][i4-2]){// jump4 i5 no4 whitefor(i5=i4-2;i5>=10;i5--){if(image_data[Row][i5-2]+V ALVE<image_data[Row][i5]){// jump5 i6 no5 blackflag_6jump=1; //total 5 jumpsi1=8;i2=8;i3=8;i4=8;i5=8;//out line scan} //end jump5} //end for} //end jump4} //end for} //end jump3}//end for(j=i-2;j>10;j--)}//end if jump2}//end for(i=k-3;i>8;i--)}//end if(image_data[Row][k-2]+V ALVE<image_data[Row][k])}//end for i1return flag_6jump;}//end jump_count//-------------------------------------------------------------------// --处理图像Process_ImgNEW//--------------------------------------------------------------------void Process_ImgNEW(void) // used to process image{unsigned char flag_right_x,JumpCount;unsigned char distance=0,temp_flag=0;unsigned char temp_black;head=1;flag_BigCurv=0;flag_Straight=0;flag_fail=0;flag_Curv=0;flag_heap=0;for(row=ROW_MAX-2;row<ROW_MAX;row++){//找近2行黑点for(line=LINE_MAX-1;line>8;line--){if(image_data[row][line]+V ALVE<image_data[row][line+3]){ //发现右点temp_black=line;for(i=1;i<10;i++){if(image_data[row][line-i]+V ALVE<image_data[row][line-i-3]){ //发现左点black_x[row]=temp_black;distance=black_x[row]-distance; //第11行-第10行中点i=10;line=8;temp_flag++;}}}}}if(temp_flag!=2) flag_fail=1;//假如找不到边界//end forif(flag_fail==0){ //计算前面黑点for(row=ROW_MAX-3;row>0;row--){ //for rowflag_right_x=0;for(line=LINE_MAX-1;line>=10;line--){ //for lineif(image_data[row][line-2]+V ALVE<image_data[row][line]){//if find right blcak_xblack_x[row]=line-2; //flag_right_x=1; //find right black_xline=8;//out line scan}}//end for lineif(flag_right_x){ //case find right black_xif(abs_sub(black_x[row],black_x[row+1])>normal_black_x)flag_black_x_normal=0;//unnormalelseflag_black_x_normal=1;//normal} //end if(flag_right_x)if(!flag_right_x){ //case not find right blcak_xif((black_x[row+1]>LINE_MAX-5)||(black_x[row+1]<12)){// the nearer row getting out visual head=row+1;row=0;// out row scan} else{ // judge as noise, cross ,or left ringblack_x[row]=black_x[row+1];//row=row-1;//next row}}//end if(!flag_right_x)if(!flag_black_x_normal){ //judge as right ring,start line or crossJumpCount=jump_6(row);if(JumpCount){//judge as start linestart_count++;black_x[row]=black_x[row+1];if(!flag_start){//when no start do thisif(start_count>=1)flag_start=1;// startif(flag_start)start_count=0;//once start,start_count restart} //end if(!flag_start)else{ //when has started do thisif(start_count==circle)flag_stop=1;//stop}}//end if(JumpCount>=6)else{ //judge as crossblack_x[row]=black_x[row+1];//row=row-1;//next row}//end else}//end if(!flag_black_x_normal)}//end for row//滤波,得到滤波后每行黑线的中心位置for(i=2;i<ROW_MAX-1;i++){temp=get_mid(black_x[i-1],black_x[i],black_x[i+1]);black_x[i]=temp;}sum=0;for(row=ROW_MAX-1;row>=head;row--){ //取黑线数组的第head行-最后一行计算中心averagesum=sum+black_x[row];}average=sum/(ROW_MAX-head);Relative_Poz=abs_sub(average,Abso_Center);if((head>r_HEAD)&&(Relative_Poz<=5))flag_heap=1; //上坡if((head>r_HEAD)&&(Relative_Poz>3))flag_BigCurv=1; //看不到头,并且相对位移大,是大弯else if((Relative_Poz<=4) &&(black_x[head]>20)&&(black_x[head]<31))flag_Straight=1; //相对位移小,可能是直线可能是小Selse{ //flag_Curv=1;//视野可见,但位移大,大Ssum=0;for(row=ROW_MAX-1;row>=6;row--){ //重计算中心averagesum=sum+black_x[row];}average=sum/(ROW_MAX-6);}}//end if not fail}//---------------------------------------------------------------------// re_setPID//---------------------------------------------------------------------void re_setPID(void){if(flag_BigCurv){steer=PWM_MID+5*(average-Abso_Center)+80*(black_x[head]-Abso_Center); speed_set=10;speed_e=speed_set-pa_count;if(pa_count-speed_set>=1){ //big reversespeed=0;rev_speed=350;}else if((pa_count-speed_set>=0)&&(pa_count-speed_set<2)){ //slowspeed=0;rev_speed=last_rev_speed-2*Kp*speed_e-Kd*(speed_e-lastspeed_e);if(rev_speed>speed_MAX) rev_speed=speed_MAX;}else{ //reverserev_speed=0;speed=lastspeed+2*Kp*speed_e+Kd*(speed_e-lastspeed_e);if(speed>speed_MAX) speed=speed_MAX;}if(pa_count<8)speed=speed_MAX;lastspeed_e=speed_e;//last_rev_speed_e=rev_speed_e;}if(flag_Straight){speed=speed_MAX; //最大速度rev_speed=0;steer=PWM_MID;lastspeed_e=0;}if(flag_fail) {//speed=lastspeed;steer=laststeer;//维持speed=150;if(laststeer-PWM_MID>100)steer=laststeer+200;else if(PWM_MID-laststeer>100)steer=laststeer-200;else steer=laststeer;}if(flag_Curv) {steer=PWM_MID+10*(average-Abso_Center)+20*(black_x[head]-Abso_Center); //转舵speed_set=speed_set_curve;speed_e=speed_set-pa_count;if(pa_count-speed_set>=0){ //slowspeed=0;rev_speed=last_rev_speed-Kp*speed_e-Kd*(speed_e-lastspeed_e);if(rev_speed>speed_MAX) rev_speed=speed_MAX;}else{ //reverserev_speed=0;speed=lastspeed+Kp*speed_e+Kd*(speed_e-lastspeed_e);if(speed>speed_MAX) speed=speed_MAX;}lastspeed_e=speed_e;//last_rev_speed_e=rev_speed_e;}if(flag_heap){speed=speed_MAX;steer=PWM_MID;}if(steer>PWM_RIGHT) steer=PWM_RIGHT;if(steer<PWM_LEFT) steer=PWM_LEFT;PWMDTY01=speed;PWMDTY23=rev_speed;PWMDTY45=steer;lastspeed=speed;last_rev_speed=rev_speed;laststeer=steer;}void key_con(void){switch(PORTA){case 0b10000000: speed_MAX=160;speed_set_curve=14;r_HEAD=3; break;case 0b11000000: speed_MAX=170;speed_set_curve=14;r_HEAD=3; break;case 0b11100000: speed_MAX=180;speed_set_curve=14;r_HEAD=3; break;case 0b11110000: speed_MAX=190;speed_set_curve=13;r_HEAD=3; break;case 0b11111000: speed_MAX=200;speed_set_curve=13;r_HEAD=3; break;case 0b11111100: speed_MAX=210;speed_set_curve=12;r_HEAD=2; break;case 0b11111110: speed_MAX=220;speed_set_curve=12;r_HEAD=2; break;case 0b11111111: speed_MAX=230;speed_set_curve=12;r_HEAD=2; break; }}//----------------------------------------------------------------------------------------//----main ------------------main----------------------main----------------------main------ //-----------------------------------------------------------------------------------------void main(void){init_PLL();init_PWM();init_PORT();init_ECT();RTI_Init();IRQCR=0x00; //diable IRQPWMDTY45=PWM_MID;PWMDTY01=0;EnableInterrupts;PWMDTY01=100;lastspeed=100;pa_count=2;flag_start=1;start_count=0;key_con();while(1){if(odd_even==1){while(odd_even==1);row=0;rowcount=0;IRQCR=0xc0;//EnableInterrupts;while(rowcount<=ROW_END) {}if(rowcount>ROW_END)IRQCR=0x00;//DisableInterrupts;Process_ImgNEW();re_setPID();}if(odd_even==0){while(odd_even==0);row=0;rowcount=0;IRQCR=0xc0;//EnableInterrupts;while(rowcount<=ROW_END) {}if(rowcount>ROW_END)IRQCR=0x00;//DisableInterrupts;Process_ImgNEW();re_setPID();}}}//----------------------------------------------------------------------------------------// -----interrupt-------------interrupt------------------interrupt-----------------interrupt //-----------------------------------------------------------------------------------------#pragma CODE_SEG NON_BANKEDvoid interrupt 6 IRQ_ISR(){rowcount++;if((rowcount>ROW_START)&&(rowcount%17==0)&&(row<ROW_MAX)) {init_AD();for(line=0;line<LINE_MAX;line++){while(!ATD0STA T2_CCF0);image_data[row][line]= A TD0DR0L;}row++;A TD0CTL2=0x00;}}//----------------------// realtime interrupt//-----------------------void interrupt 7 RTI_ISR(void){PORTB++;CRGFLG|=0x80;pa_count=PACNT;PACNT=0x00;}//------------------------------end---------------end----------------------------------。

飞思卡尔智能车完整程序

飞思卡尔智能车完整程序

#include <hidef.h> /* common defines and macros */#include <mc9s12dg128.h> /* derivative information */ #include "lib.c"#include "funtion.h"#pragma LINK_INFO DERIV ATIVE "mc9s12dg128b"void s_ini(void) //系统初始化{uchar tmp;SYNR=3;REFDV=1;PLLCTL=0x50;delay(100);CLKSEL|=0x80; //超频到48M, 总线24M// INITRG = 0x00; /* lock registers block to 0x0000 */// INITRM = 0x39; /* lock Ram to end at 0x3FFF */// INITEE = 0x09; /* lock EEPROM block to end at 0x0fff */ delay(100);PORTB=0xff;DDRB=0xff;DDRA=0x00; //A口设置为输入PTH=0x00;DDRH=0x68; //PH1=inputPERH=0x97; //enable pullPPSH=0x80; //PH7,PH6,PH5 pull up, PH4 pull down PIEH=0x00; //使能遥控中断PH7PTP =0x00;DDRP=0x30; //PP4,PP5 outputDDRA=0x00;PUCR=0x01; //Port A enable pull upPTJ=0x00;DDRJ=0x00;PERJ=0x00; //diable pullPPSJ=0x80;PIEJ=0xc0; //enable PJ interruptPTT=0x00;DDRT=0x00; //PT7-PT4 =inputPERT=0x40; //enable pull for PT6// PACN3=0x00;// PACN2=0x00;// PACTL=0x40; //enable pulse couter B// DL YCT=0x00; //TIOS=0x80; //ch 7 compare modeOC7M=0x00;OC7D=0x00;// PACTL=0x74;TSCR2=0x0f; //when ch7 compare rst pre div =128 TC7=50000; //timer for 200mS //*/TSCR1=0x80; //enable timerTCTL1=0x00;TCTL2=0x00;TCTL3=0x20;TCTL4=0x00; //通道6下降沿输入捕捉TIE =0xC0; //中断使能ini_at45(); //初始化SPI0PWME=0xc3; //enable ch1, ch7PWMPOL=0xc3; //high level effectPWMDTY6=(uchar)(3000>>8);PWMDTY7=(uchar)(3000&0x00ff); //占空比PWMPER6=(uchar)(40000>>8); // 舵机PWMPER7=(uchar)(40000&0x00ff); //周期PWMDTY0=(uchar)(0>>8);PWMDTY1=(uchar)(0&0x00ff); //占空比// PWMPER0=(uchar)(2000>>8); //电机PWMPER1=(uchar)(2000&0x00ff); //周期PWMCLK=0x00;PWMPRCLK=0x40; //SB=Fck/1 SA=Fck/8PWMCTL=0x90; //4_16 bit PWM //*/SCI0BDH=0; //串口0初始化SCI0BDL=35; //set bandrate=57600bpsSCI0CR1=0x00;SCI0CR2=0x2c; //enable to sent and receivetmp=SCI0SR1;A TD0CTL2=0xc0; //enable ATD, interruptA TD0CTL3=0x08;A TD0CTL4=0x80; //8bit,A TD1CTL2=0xc0; //enable ATD, interruptA TD1CTL3=0x08;A TD1CTL4=0x80; //8bit,A TD0DIEN=0x00; //AD口数字输入使能,使能CCD输入A TD1DIEN=0x80; //CCD二元输入ECLKDIV=0x5C; //EEPROM时钟分频器INTCR=0xc0; //行同步中断, 下降沿触发,delay(10);SE_s; //舵机供电}interrupt 20 void sci0(void) //SCI0 interrupt{uchar sta,das;sta=SCI0SR1; //read the statedas=SCI0DRL;if(sta&0x40) //sent finish{}if(sta&0x20) //receve a data{speed(das*8);SCI0DRL=das;}}interrupt 15 void ch7(void) //ch7 interrupt 266mS {TFLG1=0x80; //clr flagif(m_en) //LED falshPORTB^=0xf0;}void choice(void) //choice a funtion{uchar kv;uchar pp=0;uchar tmp=0;V1: kv=0;wu(CN1[0],CN1[1],CN1[2],CN1[3]); //displayset(2);go(0,pp); //flashfor(;;) //loop{kv=key();if(kv==5&&pp) //lastpp--,go(0,pp);else if(kv==6&&pp<3) //nextpp++,go(0,pp);if(kv==8||kv==10) //enter{if(pp==0) //进入比赛{match();goto V1;}else if(pp==1) //传感受器测方式{text();goto V1;}else if(pp==2) //CCD 测试{t_ccd();goto V1;}else if(pp==3) //参数设定{setting();goto V1;}} //*/}}void main(void) {/* put your own code here */volatile uint t1=0;s_ini(); //系统初始化EnableInterrupts;get_s(); //获取设定参数choice(); //shoicefor(;;) {} /* wait forever *//* please make sure that you never leave this function */ }/****************************************************************************** FILE : datapage.cPURPOSE : paged data access runtime routinesMACHINE : Freescale 68HC12 (Target)LANGUAGE : ANSI-CHISTORY : 21.7.96 first version created******************************************************************************/#include "hidef.h"#include "non_bank.sgm"#include "runtime.sgm"#ifndef __HCS12X__ /* it's different for the HCS12X. See the text below at the #else // __HCS12X__ *//*According to the -Cp option of the compiler the__DPAGE__, __PPAGE__ and __EPAGE__ macros are defined.If none of them is given as argument, then no page accesses should occur andthis runtime routine should not be used !To be on the save side, the runtime routines are created anyway.If some of the -Cp options are given an adapted versions which only covers theneeded cases is produced.*//* if no compiler option -Cp is given, it is assumed that all possible are given : *//* Compile with option -DHCS12 to activate this code */#if defined(HCS12) || defined(_HCS12) || defined(__HCS12__) /* HCS12 family has PPAGE register only at 0x30 */#define PPAGE_ADDR (0x30+REGISTER_BASE)#ifndef __PPAGE__ /* may be set already by option -CPPPAGE */#define __PPAGE__#endif/* Compile with option -DDG128 to activate this code */#elif defined DG128 /* HC912DG128 derivative has PPAGE register only at 0xFF */#define PPAGE_ADDR (0xFF+REGISTER_BASE)#ifndef __PPAGE__ /* may be set already by option -CPPPAGE */#define __PPAGE__#endif#elif defined(HC812A4)/* all setting default to A4 already */#endif#if !defined(__EPAGE__) && !defined(__PPAGE__) && !defined(__DPAGE__)/* as default use all page registers */#define __DPAGE__#define __EPAGE__#define __PPAGE__#endif/* modify the following defines to your memory configuration */#define EPAGE_LOW_BOUND 0x400u#define EPAGE_HIGH_BOUND 0x7ffu#define DPAGE_LOW_BOUND 0x7000u#define DPAGE_HIGH_BOUND 0x7fffu#define PPAGE_LOW_BOUND (DPAGE_HIGH_BOUND+1)#define PPAGE_HIGH_BOUND 0xBFFFu#define REGISTER_BASE 0x0u#ifndef DPAGE_ADDR#define DPAGE_ADDR (0x34u+REGISTER_BASE)#endif#ifndef EPAGE_ADDR#define EPAGE_ADDR (0x36u+REGISTER_BASE)#endif#ifndef PPAGE_ADDR#define PPAGE_ADDR (0x35u+REGISTER_BASE)#endif/*The following parts about the defines are assumed in the code of _GET_PAGE_REG :- the memory region controlled by DPAGE is above the area controlled by the EPAGE andbelow the area controlled by the PPAGE.- the lower bound of the PPAGE area is equal to be the higher bound of the DPAGE area + 1*/#if EPAGE_LOW_BOUND >= EPAGE_HIGH_BOUND || EPAGE_HIGH_BOUND >= DPAGE_LOW_BOUND || DPAGE_LOW_BOUND >= DPAGE_HIGH_BOUND || DPAGE_HIGH_BOUND >= PPAGE_LOW_BOUND || PPAGE_LOW_BOUND >= PPAGE_HIGH_BOUND#error /* please adapt _GET_PAGE_REG for this non default page configuration */#endif#if DPAGE_HIGH_BOUND+1 != PPAGE_LOW_BOUND#error /* please adapt _GET_PAGE_REG for this non default page configuration */#endif/* this module does either control if any access is in the bounds of the specified page or *//* ,if only one page is specified, just use this page. *//* This behavior is controlled by the define USE_SEVERAL_PAGES. *//* If !USE_SEVERAL_PAGES does increase the performance significantly *//* NOTE : When !USE_SEVERAL_PAGES, the page is also set for accesses outside of the area controlled *//* by this single page. But this is should not cause problems because the page is restored to the old value before any other access could occur */#if !defined(__DPAGE__) && !defined(__EPAGE__) && !defined(__PPAGE__)/* no page at all is specified *//* only specifying the right pages will speed up these functions a lot */#define USE_SEVERAL_PAGES 1#elif defined(__DPAGE__) && defined(__EPAGE__) || defined(__DPAGE__) && defined(__PPAGE__) || defined(__EPAGE__) && defined(__PPAGE__)/* more than one page register is used */#define USE_SEVERAL_PAGES 1#else#define USE_SEVERAL_PAGES 0#if defined(__DPAGE__) /* check which pages are used */#define PAGE_ADDR PPAGE_ADDR#elif defined(__EPAGE__)#define PAGE_ADDR EPAGE_ADDR#elif defined(__PPAGE__)#define PAGE_ADDR PPAGE_ADDR#else /* we do not know which page, decide it at runtime */#error /* must not happen */#endif#endif#if USE_SEVERAL_PAGES /* only needed for several pages support *//*--------------------------- _GET_PAGE_REG --------------------------------Runtime routine to detect the right register depending on the 16 bit offset partof an address.This function is only used by the functions below.Depending on the compiler options -Cp different versions of _GET_PAGE_REG are produced.Arguments :- Y : offset part of an addressResult :if address Y is controlled by a page register :- X : address of page register if Y is controlled by an page register- Zero flag cleared- all other registers remain unchangedif address Y is not controlled by a page register :- Zero flag is set- all registers remain unchanged--------------------------- _GET_PAGE_REG ----------------------------------*/#if defined(__DPAGE__)#ifdef __cplusplusextern "C"#endif#pragma NO_ENTRY#pragma NO_EXIT#pragma NO_FRAMEstatic void NEAR _GET_PAGE_REG(void) { /*lint -esym(528, _GET_PAGE_REG) used in asm code */__asm {L_DPAGE:CPY #DPAGE_LOW_BOUND ;// test of lower bound of DPAGE#if defined(__EPAGE__)BLO L_EPAGE ;// EPAGE accesses are possible#elseBLO L_NOPAGE ;// no paged memory below accesses#endifCPY #DPAGE_HIGH_BOUND ;// test of higher bound DPAGE/lower bound PPAGE#if defined(__PPAGE__)BHI L_PPAGE ;// EPAGE accesses are possible#elseBHI L_NOPAGE ;// no paged memory above accesses#endifFOUND_DPAGE:LDX #DPAGE_ADDR ;// load page register address and clear zero flagRTS#if defined(__PPAGE__)L_PPAGE:CPY #PPAGE_HIGH_BOUND ;// test of higher bound of PPAGEBHI L_NOPAGEFOUND_PPAGE:LDX #PPAGE_ADDR ;// load page register address and clear zero flagRTS#endif#if defined(__EPAGE__)L_EPAGE:CPY #EPAGE_LOW_BOUND ;// test of lower bound of EPAGEBLO L_NOPAGECPY #EPAGE_HIGH_BOUND ;// test of higher bound of EPAGEBHI L_NOPAGEFOUND_EPAGE:LDX #EPAGE_ADDR ;// load page register address and clear zero flagRTS#endifL_NOPAGE:ORCC #0x04 ;// sets zero flagRTS}}#else /* !defined(__DPAGE__) */#if defined( __PPAGE__ )#ifdef __cplusplusextern "C"#endif#pragma NO_ENTRY#pragma NO_EXIT#pragma NO_FRAMEstatic void NEAR _GET_PAGE_REG(void) { /*lint -esym(528, _GET_PAGE_REG) used in asm code */__asm {L_PPAGE:CPY #PPAGE_LOW_BOUND ;// test of lower bound of PPAGE#if defined( __EPAGE__ )BLO L_EPAGE#elseBLO L_NOPAGE ;// no paged memory below#endifCPY #PPAGE_HIGH_BOUND ;// test of higher bound PPAGEBHI L_NOPAGEFOUND_PPAGE:LDX #PPAGE_ADDR ;// load page register address and clear zero flagRTS#if defined( __EPAGE__ )L_EPAGE:CPY #EPAGE_LOW_BOUND ;// test of lower bound of EPAGEBLO L_NOPAGECPY #EPAGE_HIGH_BOUND ;// test of higher bound of EPAGEBHI L_NOPAGEFOUND_EPAGE:LDX #EPAGE_ADDR ;// load page register address and clear zero flagRTS#endifL_NOPAGE: ;// not in any allowed page area;// its a far access to a non paged variableORCC #0x04 ;// sets zero flagRTS}}#else /* !defined(__DPAGE__ ) && !defined( __PPAGE__) */#if defined(__EPAGE__)#ifdef __cplusplusextern "C"#endif#pragma NO_ENTRY#pragma NO_EXIT#pragma NO_FRAMEstatic void NEAR _GET_PAGE_REG(void) { /*lint -esym(528, _GET_PAGE_REG) used in asm code */__asm {L_EPAGE:CPY #EPAGE_LOW_BOUND ;// test of lower bound of EPAGEBLO L_NOPAGECPY #EPAGE_HIGH_BOUND ;// test of higher bound of EPAGEBHI L_NOPAGEFOUND_EPAGE:LDX #EPAGE_ADDR ;// load page register address and clear zero flagRTSL_NOPAGE: ;// not in any allowed page area;// its a far access to a non paged variableORCC #0x04 ;// sets zero flagRTS}}#endif /* defined(__EPAGE__) */#endif /* defined(__PPAGE__) */#endif /* defined(__DPAGE__) */#endif /* USE_SEVERAL_PAGES *//*--------------------------- _SET_PAGE --------------------------------Runtime routine to set the right page register. This routine is used if the compilerdoes not know the right page register, i.e. if the option -Cp is used for more thanone pageregister or if the runtime option is used for one of the -Cp options.Arguments :- offset part of an address in the Y register- page part of an address in the B registerResult :- page part written into the correct page register.- the old page register content is destroyed- all processor registers remains unchanged--------------------------- _SET_PAGE ----------------------------------*/#ifdef __cplusplusextern "C"#endif#pragma NO_ENTRY#pragma NO_EXIT#pragma NO_FRAMEvoid NEAR _SET_PAGE(void) {#if USE_SEVERAL_PAGES__asm {PSHX ;// save X register__PIC_JSR(_GET_PAGE_REG)BEQ L_NOPAGESTAB 0,X ;// set page registerL_NOPAGE:PULX ;// restore X registerRTS}#else /* USE_SEVERAL_PAGES */__asm {STAB PAGE_ADDR ;// set page registerRTS}#endif /* USE_SEVERAL_PAGES */}/*--------------------------- _LOAD_FAR_8 --------------------------------This runtime routine is used to access paged memory via a runtime function.It may also be used if the compiler option -Cp is not used with the runtime argument.Arguments :- offset part of an address in the Y register- page part of an address in the B registerResult :- value to be read in the B register- all other registers remains unchanged- all page register still contain the same value--------------------------- _LOAD_FAR_8 ----------------------------------*/#ifdef __cplusplusextern "C"#endif#pragma NO_ENTRY#pragma NO_EXIT#pragma NO_FRAMEvoid NEAR _LOAD_FAR_8(void) {#if USE_SEVERAL_PAGES__asm {PSHX ;// save X register__PIC_JSR(_GET_PAGE_REG)BEQ L_NOPAGEPSHA ;// save A registerLDAA 0,X ;// save page registerSTAB 0,X ;// set page registerLDAB 0,Y ;// actual load, overwrites pageSTAA 0,X ;// restore page registerPULA ;// restore A registerPULX ;// restore X registerRTSL_NOPAGE:LDAB 0,Y ;// actual load, overwrites pagePULX ;// restore X registerRTS}#else /* USE_SEVERAL_PAGES */__asm {PSHA ;// save A registerLDAA PAGE_ADDR ;// save page registerSTAB PAGE_ADDR ;// set page registerLDAB 0,Y ;// actual load, overwrites pageSTAA PAGE_ADDR ;// restore page registerPULA ;// restore A registerRTS}#endif /* USE_SEVERAL_PAGES */}/*--------------------------- _LOAD_FAR_16 --------------------------------This runtime routine is used to access paged memory via a runtime function.It may also be used if the compiler option -Cp is not used with the runtime argument.Arguments :- offset part of an address in the Y register- page part of an address in the B registerResult :- value to be read in the Y register- all other registers remains unchanged- all page register still contain the same value--------------------------- _LOAD_FAR_16 ----------------------------------*/#ifdef __cplusplusextern "C"#endif#pragma NO_ENTRY#pragma NO_EXIT#pragma NO_FRAMEvoid NEAR _LOAD_FAR_16(void) {#if USE_SEVERAL_PAGES__asm {PSHX ;// save X register__PIC_JSR(_GET_PAGE_REG)BEQ L_NOPAGEPSHA ;// save A registerLDAA 0,X ;// save page registerSTAB 0,X ;// set page registerLDY 0,Y ;// actual load, overwrites addressSTAA 0,X ;// restore page registerPULA ;// restore A registerPULX ;// restore X registerRTSL_NOPAGE:LDY 0,Y ;// actual load, overwrites addressPULX ;// restore X registerRTS}#else /* USE_SEVERAL_PAGES */__asm {PSHA ;// save A registerLDAA PAGE_ADDR ;// save page registerSTAB PAGE_ADDR ;// set page registerLDY 0,Y ;// actual load, overwrites addressSTAA PAGE_ADDR ;// restore page registerPULA ;// restore A registerRTS}#endif /* USE_SEVERAL_PAGES */}/*--------------------------- _LOAD_FAR_24 --------------------------------This runtime routine is used to access paged memory via a runtime function.It may also be used if the compiler option -Cp is not used with the runtime argument. Arguments :- offset part of an address in the Y register- page part of an address in the B registerResult :- value to be read in the Y:B registers- all other registers remains unchanged- all page register still contain the same value--------------------------- _LOAD_FAR_24 ----------------------------------*/#ifdef __cplusplusextern "C"#endif#pragma NO_ENTRY#pragma NO_EXIT#pragma NO_FRAMEvoid NEAR _LOAD_FAR_24(void) {#if USE_SEVERAL_PAGES__asm {PSHX ;// save X register__PIC_JSR(_GET_PAGE_REG)BEQ L_NOPAGEPSHA ;// save A registerLDAA 0,X ;// save page registerSTAB 0,X ;// set page registerLDAB 0,Y ;// actual load, overwrites page of addressLDY 1,Y ;// actual load, overwrites offset of addressSTAA 0,X ;// restore page registerPULA ;// restore A registerPULX ;// restore X registerRTSL_NOPAGE:LDAB 0,Y ;// actual load, overwrites page of addressLDY 1,Y ;// actual load, overwrites offset of addressPULX ;// restore X registerRTS}#else /* USE_SEVERAL_PAGES */__asm {PSHA ;// save A registerLDAA PAGE_ADDR ;// save page registerSTAB PAGE_ADDR ;// set page registerLDAB 0,Y ;// actual load, overwrites page of addressLDY 1,Y ;// actual load, overwrites offset of addressSTAA PAGE_ADDR ;// restore page registerPULA ;// restore A registerRTS}#endif /* USE_SEVERAL_PAGES */}/*--------------------------- _LOAD_FAR_32 --------------------------------This runtime routine is used to access paged memory via a runtime function.It may also be used if the compiler option -Cp is not used with the runtime argument.Arguments :- offset part of an address in the Y register- page part of an address in the B registerResult :- low 16 bit of value to be read in the D registers- high 16 bit of value to be read in the Y registers- all other registers remains unchanged- all page register still contain the same value--------------------------- _LOAD_FAR_32 ----------------------------------*/#ifdef __cplusplusextern "C"#endif#pragma NO_ENTRY#pragma NO_EXIT#pragma NO_FRAMEvoid NEAR _LOAD_FAR_32(void) {#if USE_SEVERAL_PAGES__asm {PSHX ;// save X register__PIC_JSR(_GET_PAGE_REG)BEQ L_NOPAGELDAA 0,X ;// save page registerPSHA ;// put it onto the stackSTAB 0,X ;// set page registerLDD 2,Y ;// actual load, low wordLDY 0,Y ;// actual load, high wordMOVB 1,SP+,0,X ;// restore page registerPULX ;// restore X registerRTSL_NOPAGE:LDD 2,Y ;// actual load, low wordLDY 0,Y ;// actual load, high wordPULX ;// restore X registerRTS}#else /* USE_SEVERAL_PAGES */__asm {LDAA PAGE_ADDR ;// save page registerPSHA ;// put it onto the stackSTAB PAGE_ADDR ;// set page registerLDD 2,Y ;// actual load, low wordLDY 0,Y ;// actual load, high wordMOVB 1,SP+,PAGE_ADDR ;// restore page registerRTS}#endif /* USE_SEVERAL_PAGES */}/*--------------------------- _STORE_FAR_8 --------------------------------This runtime routine is used to access paged memory via a runtime function.It may also be used if the compiler option -Cp is not used with the runtime argument.Arguments :- offset part of an address in the Y register- page part of an address in the B register- value to be stored in the B registerResult :- value stored at the address- all registers remains unchanged- all page register still contain the same value--------------------------- _STORE_FAR_8 ----------------------------------*/#ifdef __cplusplusextern "C"#endif#pragma NO_ENTRY#pragma NO_EXIT#pragma NO_FRAMEvoid NEAR _STORE_FAR_8(void) {#if USE_SEVERAL_PAGES__asm {PSHX ;// save X register__PIC_JSR(_GET_PAGE_REG)BEQ L_NOPAGEPSHB ;// save B registerLDAB 0,X ;// save page registerMOVB 0,SP, 0,X ;// set page registerSTAA 0,Y ;// store the value passed in ASTAB 0,X ;// restore page registerPULB ;// restore B registerPULX ;// restore X registerRTSL_NOPAGE:STAA 0,Y ;// store the value passed in APULX ;// restore X registerRTS}#else /* USE_SEVERAL_PAGES */__asm {PSHB ;// save A registerLDAB PAGE_ADDR ;// save page registerMOVB 0,SP,PAGE_ADDR ;// set page registerSTAA 0,Y ;// store the value passed in ASTAB PAGE_ADDR ;// restore page registerPULB ;// restore B registerRTS}#endif /* USE_SEVERAL_PAGES */}/*--------------------------- _STORE_FAR_16 --------------------------------This runtime routine is used to access paged memory via a runtime function.It may also be used if the compiler option -Cp is not used with the runtime argument.Arguments :- offset part of an address in the Y register- page part of an address in the B register- value to be stored in the X registerResult :- value stored at the address- all registers remains unchanged- all page register still contain the same value--------------------------- _STORE_FAR_16 ----------------------------------*/#ifdef __cplusplusextern "C"#endif#pragma NO_ENTRY#pragma NO_EXIT#pragma NO_FRAMEvoid NEAR _STORE_FAR_16(void) {#if USE_SEVERAL_PAGES__asm {PSHX ;// save X register__PIC_JSR(_GET_PAGE_REG)BEQ L_NOPAGEPSHALDAA 0,X ;// save page registerSTAB 0,X ;// set page registerMOVW 1,SP,0,Y ;// store the value passed in XSTAA 0,X ;// restore page registerPULA ;// restore A registerPULX ;// restore X registerRTSL_NOPAGE:STX 0,Y ;// store the value passed in XPULX ;// restore X registerRTS}#else /* USE_SEVERAL_PAGES */__asm {PSHA ;// save A registerLDAA PAGE_ADDR ;// save page registerSTAB PAGE_ADDR ;// set page registerSTX 0,Y ;// store the value passed in XSTAA PAGE_ADDR ;// restore page registerPULA ;// restore A registerRTS}#endif /* USE_SEVERAL_PAGES */}/*--------------------------- _STORE_FAR_24 --------------------------------This runtime routine is used to access paged memory via a runtime function.It may also be used if the compiler option -Cp is not used with the runtime argument.Arguments :- offset part of an address in the Y register- page part of an address in the B register- value to be stored in the X:A registers (X : low 16 bit, A : high 8 bit)Result :- value stored at the address- all registers remains unchanged- all page register still contain the same value--------------------------- _STORE_FAR_24 ----------------------------------*/#ifdef __cplusplusextern "C"#endif#pragma NO_ENTRY#pragma NO_EXIT#pragma NO_FRAMEvoid NEAR _STORE_FAR_24(void) {#if USE_SEVERAL_PAGES__asm {PSHX ;// save X register__PIC_JSR(_GET_PAGE_REG)BEQ L_NOPAGEPSHALDAA 0,X ;// save page registerSTAB 0,X ;// set page registerMOVW 1,SP, 1,Y ;// store the value passed in XMOVB 0,SP, 0,Y ;// store the value passed in ASTAA 0,X ;// restore page registerPULA ;// restore A registerPULX ;// restore X registerRTSL_NOPAGE:STX 1,Y ;// store the value passed in XSTAA 0,Y ;// store the value passed in XPULX ;// restore X registerRTS}#else /* USE_SEVERAL_PAGES */__asm {PSHA ;// save A registerLDAA PAGE_ADDR ;// save page registerSTAB PAGE_ADDR ;// set page registerMOVB 0,SP, 0,Y ;// store the value passed in ASTX 1,Y ;// store the value passed in XSTAA PAGE_ADDR ;// restore page registerPULA ;// restore A registerRTS}#endif /* USE_SEVERAL_PAGES */}/*--------------------------- _STORE_FAR_32 --------------------------------This runtime routine is used to access paged memory via a runtime function.It may also be used if the compiler option -Cp is not used with the runtime argument.Arguments :- offset part of an address in the Y register- page part of an address is on the stack at 3,SP (just below the return address)- value to be stored in the X:D registers (D : low 16 bit, X : high 16 bit)Result :- value stored at the address- all registers remains unchanged- the page part is removed from the stack- all page register still contain the same value--------------------------- _STORE_FAR_32 ----------------------------------*/#ifdef __cplusplusextern "C"#endif#pragma NO_ENTRY#pragma NO_EXIT#pragma NO_FRAMEvoid NEAR _STORE_FAR_32(void) {#if USE_SEVERAL_PAGES__asm {PSHX ;// save X register__PIC_JSR(_GET_PAGE_REG)BEQ L_NOPAGEPSHDLDAA 0,X ;// save page registerMOVB 6,SP, 0,X ;// set page registerMOVW 2,SP, 0,Y ;// store the value passed in X (high word)MOVW 0,SP, 2,Y ;// store the value passed in D (low word)STAA 0,X ;// restore page registerPULD ;// restore A registerBRA doneL_NOPAGE:MOVW 0,SP, 0,Y ;// store the value passed in X (high word)STD 2,Y ;// store the value passed in D (low word) done:PULX ;// restore X registerMOVW 0,SP, 1,+SP ;// move return addressRTS}#else /* USE_SEVERAL_PAGES */__asm {PSHD ;// save D registerLDAA PAGE_ADDR ;// save page registerLDAB 4,SP ;// load page part of addressSTAB PAGE_ADDR ;// set page registerSTX 0,Y ;// store the value passed in XMOVW 0,SP, 2,Y ;// store the value passed in D (low word)STAA PAGE_ADDR ;// restore page registerPULD ;// restore D registerMOVW 0,SP, 1,+SP ;// move return addressRTS}#endif /* USE_SEVERAL_PAGES */}/*--------------------------- _FAR_COPY_RC --------------------------------This runtime routine is used to access paged memory via a runtime function.It may also be used if the compiler option -Cp is not used with the runtime argument.Arguments :- offset part of the source int the X register- page part of the source in the A register- offset part of the dest int the Y register- page part of the dest in the B register- number of bytes to be copied is defined by the next 2 bytes after the return address.Result :- memory area copied- no registers are saved, i.e. all registers may be destroyed- all page register still contain the same value as before the call- the function returns after the constant defining the number of bytes to be copiedstack-structure at the loop-label:0,SP : destination offset2,SP : source page3,SP : destination page4,SP : source offset6,SP : points to length to be copied. This function returns after the sizeA usual call to this function looks like:struct Huge src, dest;; ...LDX #srcLDAA #PAGE(src)LDY #destLDAB #PAGE(dest)JSR _FAR_COPY_RCDC.W sizeof(struct Huge); ...--------------------------- _FAR_COPY_RC ----------------------------------*/#ifdef __cplusplusextern "C"#endif#pragma NO_ENTRY#pragma NO_EXIT#pragma NO_FRAMEvoid NEAR _FAR_COPY_RC(void) {#if USE_SEVERAL_PAGES__asm {DEX ;// source addr-=1, because loop counter ends at 1PSHX ;// save source offsetPSHD ;// save both pagesDEY ;// destination addr-=1, because loop counter ends at 1PSHY ;// save destination offsetLDY 6,SP ;// Load Return addressLDX 2,Y+ ;// Load Size to copySTY 6,SP ;// Store adjusted return addressloop:LDD 4,SP ;// load source offset。

飞思科尔光电组程序

飞思科尔光电组程序

我是光电组的,下面是程序,小车可以跑起来,但速度有待提升#include <hidef.h> /* common defines and macros */#include <MC9S12XS128.h> /* derivative information */#pragma LINK_INFO DERIVATIVE "mc9s12xs128"//static unsigned chardirection_turn[12]={888,1098,1208,1328,1481,1612,1730,1856,1988,2100,22 22,2368};//Chapter 12//Periodic Interrupt Timer (S12PIT24B4CV1) Page349//The PIT module has no external pins.//PIT 模式没有外部引脚//========================================================== ==============================unsigned char light=0; //激光管检测标志unsigned short turn_value=0; //转向的PWM数值unsigned short direction_turn[7]={333,430,560,647,705,780,888}; //转向给定值初始化short speed_set[7]={250,300,350,400,350,300,250}; //速度给定值short speed_flag=0; //速度档位标志位short speed[3]={0,0,0}; //速度检测函数short pulse_count=0; //编码器脉冲计数值short speed_expect=0; //理想速度short kp=2; //比例环节short ki=0; //积分环节short kd=1; //微分环节short ek1=0; //误差1short ek2=0; //误差2short ek3=0; //误差3short speed_add=0; //速度增量//========================================================== =============================void PLL_Init() //时钟初始化{REFDV=0x81; /*PLLCLK=2*OSCCLK*(SYNR+1)/(REFDV+1)*/SYNR=2; /* 锁相环时钟=2*16*(2+1)/(1+1)=48MHZ */while(!(CRGFLG&0x08)); /* 总线时钟=48/2=24MHZ */CLKSEL=0x80;}void PWM_Init() //PWM初始化{PWME=0x00; //关闭PWM使能PWMPRCLK=0x66; //A,B时钟均为总线的64分频,375KHZ//PWMSCLA=0x01; //clockSA=clockA/(2*PWMSCLA) = 1500KHZ //PWMSCLB=0X01; //clockSB=clockB/(2*PWMSCLB) =1500KHZ PWMCLK=0x00;PWMPOL=0xFF; //PWM输出起始电平为高电平PWMCAE=0x00; //输出左对齐PWMCTL=0xf0; //通道01,23,45,67级联PWMPER01=5999; //舵机频率为62.5HzPWMDTY01=647; //占空比a=(PWMDTY01+1)/(PWMPER01+1) PWMPER23=1000; //PWM通道3周期为375HZPWMDTY23=0; //占空比a=(PWMDTY01+1)/(PWMPER01+1)占空比50% ~~ 150PWMPER45=1000; //PWM通道5周期为0.10ms 10KZH300=0.00010/(1/3000000)PWMDTY45=300; //占空比a=(PWMDTY01+1)/(PWMPER01+1)PWMPER67=375; //频率为1000HzPWMDTY67=200; //PWME=0xff; //使能pwm}void Pit0_Init() //PIT初始化{PITCFLMT_PITE=0; //关PIT使能PITCE_PCE0=1; //通道0使能PITMUX_PMUX0=0; //通道0接微时钟0PITMTLD0=99; //微时钟0值设置为7fPITLD0=3839; //time-out period = (PITMTLD + 1) * (PITLD + 1) / fBUS.//时间计算100*3840/24000000=0.016s PITINTE_PINTE0=1; //通道0中断时能PITCFLMT_PITE=1; //PIT使能}void ECT_Init(){TIOS=0x00; /* OC0路为输出比较,OC1路为输入捕捉*/TSCR2=0x06; /* 定时器溢出中断禁止,计数器自由运行禁止复位,64分频*/TSCR1=0x80; /* 定时器使能*/TIE=0x01; /* 输出比较相应中断使能*/TCTL4=0x01;}void dly_1ms(){int i,j;for(i=0;i<200;i++){for(j=0;j<1000;j++){;}}}void sam_position() //车位检测函数{int i=0,j=0;unsigned char m=0,n=0;n=PORTA;for(i;i<10;i++){m=PORTA;if(n==m)j++;}if(j>6)light=n;}void check_start() //检测起始线{if((light&&4)||(light&&16))start_flag++;}void check_start(){}void turning() //舵机转向函数{switch(light){case 1:if(turn_value==direction_turn[1]) //出界判断算法{turn_value=direction_turn[0];speed_expect=speed_set[0];}else if(turn_value==direction_turn[0]){turn_value=direction_turn[0];speed_expect=speed_set[0];}break;case 2:if(turn_value==direction_turn[0]){turn_value=direction_turn[1];speed_expect=speed_set[1];}else if(turn_value==direction_turn[1]){turn_value=direction_turn[1];speed_expect=speed_set[1];}else if(turn_value==direction_turn[2]){turn_value=direction_turn[1];speed_expect=speed_set[1];}break;case 4:if(turn_value==direction_turn[1]){turn_value=direction_turn[2];speed_expect=speed_set[2];}else if(turn_value==direction_turn[2]){turn_value=direction_turn[2];speed_expect=speed_set[2];}else if(turn_value==direction_turn[3]){turn_value=direction_turn[2];speed_expect=speed_set[2];}break;case 8:if(turn_value==direction_turn[2]){turn_value=direction_turn[3];speed_expect=speed_set[3];}else if(turn_value==direction_turn[3]){turn_value=direction_turn[3];speed_expect=speed_set[3];}else if(turn_value==direction_turn[4]){turn_value=direction_turn[3];speed_expect=speed_set[3];}break;case 16:if(turn_value==direction_turn[3]){turn_value=direction_turn[4];speed_expect=speed_set[4];}else if(turn_value==direction_turn[4]){turn_value=direction_turn[4];speed_expect=speed_set[4];}else if(turn_value==direction_turn[5]){turn_value=direction_turn[4];speed_expect=speed_set[4];}break;case 32:if(turn_value==direction_turn[4]){turn_value=direction_turn[5];speed_expect=speed_set[5];}else if(turn_value==direction_turn[5]){turn_value=direction_turn[5];speed_expect=speed_set[5];}else if(turn_value==direction_turn[6]){turn_value=direction_turn[5];speed_expect=speed_set[5];}break;case 64:if(turn_value==direction_turn[5]) //出界判断算法{turn_value=direction_turn[6];speed_expect=speed_set[6];}else if(turn_value==direction_turn[6]){turn_value=direction_turn[6];speed_expect=speed_set[6];}break;default:break;}PWMDTY01=turn_value;}void check_speed() //速度检测函数{ek3=ek2; //计算速度差值ek2=ek1;ek1=speed_expect-pulse_count;speed[2]=speed[1]; //当前速度放在[0],之前放在[1],[2]speed[1]=speed[0];speed[0]=pulse_count;pulse_count=0;}void speed_down() //制动函数{PWMDTY23=300; //电机反向供电PWMDTY45=0;}void speed_pid() //PID算法{speed_add=kp*(ek1-ek2)+ki*ek1+kd*(ek1-2*ek2+ek3); //PID增量式}void driver() //驱动电机控制函数{//if(((turn_value>705)||(turn_value<560))&&(speed[0]>200)) //当前速度若远超给定速度// {//speed_down();// }//else// {PWMDTY23=0;speed_pid();PWMDTY45=PWMDTY45+speed_add;// }if(PWMDTY45>600)PWMDTY45=600;}void main(){DisableInterrupts; /* 关中断*/PLL_Init();PWM_Init();Pit0_Init();ECT_Init();turn_value=direction_turn[3];DDRA=0x00;DDRB=0xFF;PORTB=0X00;EnableInterrupts;for(;;){//sam_position();//turning();}}#pragma CODE_SEG NON_BANKEDvoid interrupt 8 Timer0_ISR(void){pulse_count++;TFLG1_C0F=1; /* TC0端有中断产生*/ }void interrupt 66 PIT0_ISR(void){sam_position(); //车位检测函数turning(); //舵机转向函数check_speed(); //速度检测函数driver(); // 驱动电机控制函数PITTF_PTF0=1; /* PIT0端有中断产生,清除标志位*/ }。

飞思卡尔PWM程序(含详细指令说明)

飞思卡尔PWM程序(含详细指令说明)
//4、5 通道可选用 A、SA 时钟,2、3、6、7 通道可选用 B、SB 通道。此寄存器
//在任何时间都是可读、可写的,复位时全置0。应当注意的是,如果当一个 PWM
//输出波形正在产生时,时钟改变,这时就会产生一个平头的或线形脉冲。
//用法: PCLK1=1; 1 通道的时钟源设为 SA。 PCLK1=0; 1 通道的时钟源设为 A。
//如果通道不可用,那么对周期寄存器进行写操作,将会直接导致周期寄存器同缓冲器一起
//闭锁。
//周期的计算方法:(因为左对齐和居中对齐方式输出时的计数器工作方式不一样)
//1) 当 CAEx=0时,即进行左线性输出时:
// `PWMx 周期=通道时钟周期*PWMPERx
PWMPOL_PPOL3=1; // Duty=High Time 极性设置
//3通道对外输出为先高后低(PWMPOL_PPOL3=0 则3通道对外输出为先低后高)
PWMCAE_CAE3=0; // Left-aligned 对齐方式设置
//------------------------------------------------------------------------------------------------------------------//
//功能说明:MC9S12XS128--PWM例程
//使用说明:实现通道3(PTP3)输出频率为1KHz,占空比为50%的方波,用示波器观察
//决定了相关 PWM 通道的周期。 每一个通道的周期寄存器都是双缓冲的,因此如果当通
//道使能后,改变他们的值,将不会发生任何作用,除非当下列情况之一发生:
//*有效的周期结束。

飞思卡尔光电程序

飞思卡尔光电程序

/*文件名:main.c硬件:MC9SDG128Bclk=16m编译:CodeWarrior*/#include <hidef.h> /* common defines and macros */#include <mc9s12dg128.h> /* derivative information */#pragma LINK_INFO DERIV ATIVE "mc9s12dg128b"#include<string.h>#include "printp.h"#include "math.h"//------------------------PID函数-----------------------------static int set_integration=80;static int dError,Error;static int SetPoint=50;//初始值设置static int Proportion=7; //比例Kstatic int Integral=70;//set_integration; // 积分T*K/Ti static int Derivative=50; // 微分K*Td/Tstatic int Proportion2=1; //比例Kstatic int Integral2=70;//set_integration; // 积分T*K/Ti static int Derivative2=15; // 微分K*Td/Tstatic int LastError=0; // Error[-1]static int PrevError=0; // Error[-2]static int Point_lineroad = 140 ;static int Point_sturnroad = 90 ;static int Point_bigturnroad = 90 ;static int Point_gooutroadlittle = 80 ;static int Point_gooutroadbig = 80 ;static int Point_littlebig = 100;static int Point_gooutroadnoline = 70 ;static int Point_nearlineroad = 90 ;static int Point_Add = 0 ;//-------------------舵机PD-----static int PD_SetPoint=0;//初始值设置static int PD_Proportion=15; //比例Kstatic int PD_Derivative=1; // 微分K*Td/Tstatic int PD_LastError=0; // Error[-1]static int PD_PrevError=0; // Error[-2]static int PD_dError,PD_Error,PD_rout,PD_RError;static int i_Position,PD_i_Position; //黑线位置辽宁工程技术大学毕业设计(论文)static int Position[7]={-460,-300,-150,0,150,300,460};static unsigned int Position_R[7]={150,150,150,150,150,150};static int Vs;static int Vf;//++++++++++++++++++++舵机相关++++++++++++++++++++++++++++++++++++++static int turn_control=0,oldturn_control=0;static unsigned char turn_filter_count=0;static unsigned char crossroad; //十字路口//---------------------电机相关--------------------------------------static unsigned int uint_Array_SetSpeed_line[7] ={80,80,80,80,80,80};static unsigned int *point_uint_SetSpeed= uint_Array_SetSpeed_line;static unsigned int wheel_speed_p=0,wheel_speed=0;static int rout,rin; //pid parmeterstatic int control=0,old_control;//control=100;static int delay;//---------------------输入捕捉相关----------------------------------static unsigned int Time_inCapture,count=0;static unsigned int Average_inCatime,Average_inCapturetime[4]={0,0,0,0};static unsigned int go=0,see_noline=0,see_blackline=0,backline_flag,see_gonow;static unsigned char go_flag=0;static unsigned int N=0,P=0; //speedstatic void wait(long ms){long timeout;timeout = ui_absoluteTime + ms;while (timeout != ui_absoluteTime){__asm NOP;timeout = timeout-1; /* __asm WAI; */ /* will be waken up by the RTI exception. Not well supported in BDM mode */}}void ADCInit(void){ATD0CTL2=0xC0; //EAD模块上电, 快速清零, 无等待模式, 禁止外部触发ATD0CTL3=0X38; // 每个序列7次转换, No FIFO, Freeze模式下继续转换ATD0CTL4=0x81; // 8位精度, 2个时钟,2uS ATDClock=[BusClock*0.5]/[PRS+1] ; PRS=1, divider=4ATD0CTL5=0xb0; //右对齐无符号,多通道采样,通道0开始至6ATD0DIEN=0x00; // 禁止数字输入ATD0CTL2=0xC0; //EAD模块上电, 快速清零, 无等待模式, 禁止外部触发,允许中?}{PLLCTL=0XF1;SYNR=0X02;REFDV=0X01;CRGFLG=0X40;while((CRGFLG!=0X0C)&(CRGFLG!=0X1C)) { ;}CLKSEL=0X80;}void SciInit(){SCI0BDL = (unsigned char)((48000000UL / 2) / 9600/ 16);SCI0CR1=0; /*normal,no parity*/SCI0CR2=0X08; /*RIE=1,TE=1,RE=1*/}void IRT_INIT(void){RTICTL=0x39; //0.00256中断一次CRGINT=0x80;}void Time_MCC(){MCCTL=0xc7;MCCNT=0x2710;}//-----------------------pwm---------------------------------void pwm_init(void){//设置前进方向PWMCAE =0x00; /*LIFE ALIGE 左对齐*/PWMPRCLK =0x13; /*pwm a分频128,b分频2*/ //a 32PWMPOL =0xAa; /*通道1和3上升开始*/PWMCTL =0xF0; /*01,23为16位输出*/PWMCLK =0x00; /*选择阿01A 23B时钟*/PWMPER01 =37500; /*设置脉冲个数1875 输出100Hz,128分频8分频37500 80Hz*/PWMDTY01 =turn_middle ; //240--340// -42度到+42度PWMPER23 =1281; /*设置脉冲个数输出10KHz 6000是2KHz*/PWMDTY23 =1000; //700PWMPER45 =1875;PWMDTY45 =c_midile; // 255 //355right hi 155辽宁工程技术大学毕业设计(论文)PWMDTY67 =0;PWME =0x02; /*打开P1和P3口*/DDRP=0xff; //设置控制输出PTP=0XFE;}//======================capture====================================void capture_init(void){TIOS=0X00; //输入捕捉0口TCTL4=0X02; //扑捉falling edge沿TIE=0X01; //开扑捉中断TSCR2=0X07; //分频128分频TSCR2_TOI=1;开溢出中断TFLG1_C0F=1; //置位标志位TFLG2_TOF=1; //置标志位TSCR1=0X80; //开定时器,标志位自动清零TSCR2_TOI=1;}//++++++++++++++++++++++++++EEROM+++++++++++++++++++++++++++++++++++ void eeprom_program(uint data,uint addr){uint *p;p = (uint*)addr;ECLKDIV = 0x4a; //设置时钟ESTAT=ESTA T_PVIOL_MASK+ESTAT_ACCERR_MASK; //清出错标志位*p=data;ECMD=prog; //赋命令ESTAT_CBEIF = 1; //清缓存标志位if((ESTA T_PVIOL==0)&&(ESTAT_ACCERR==0)){while(!ESTA T_CCIF); // 等待命令执行完成}}void eeprom_erase(uint addr) //擦数据addr将数据从地址开始位擦出{uint *p;p = (uint*)addr;ECLKDIV = 0x4a; //设置时钟ESTAT=ESTA T_PVIOL_MASK+ESTAT_ACCERR_MASK; //清出错标志位*p=0xffff;ECMD=sector_erase; //赋命令ESTAT_CBEIF = 1; //清缓存标志位{while(!ESTA T_CCIF); // 等待命令执行完成}}void eeprom_init(void){INITEE=0x41; //eeprom地址从0x4000到0x47ff; asm NOP;MISC=1;}void PH_INIT(void){DDRH=0X00;PERH=0XFF; //PULL UP PULL DOWN DEVICE is enabled PPSH =0X00; //Falling edge up pull PIEH=0XFF; //interupt p0 enable }//++++++++++刹车++++++++++++++++++++++++++++++++++++++++++++++void brake_car(){back_car;PWMDTY23=300; //>300_asm("nop");_asm("nop");_asm("nop");_asm("nop");forward_car;}//----------------------------------------------------------------------------------void PID_speed_control_2(){wheel_speed= Time_inCapture;wheel_speed=60000/wheel_speed ; // rin值越大,速度越快rin =(int)(wheel_speed); // rin=90:1meter rin=120;;2meter Error = SetPoint-rin; // 积分dError = Error-2*LastError + PrevError; // 微分项rout=((Proportion2*(Error-LastError)) +(Integral2*Error)+(Derivative2*dError));PrevError = LastError; // 偏差存储LastError = Error; // 偏差存储辽宁工程技术大学毕业设计(论文)// control =control+(rout/set_integration);old_control = control ;control =control+(rout/80);//----------------------限制加速度----------------------------------------- if( Average_inCatime > 900 )car_static = stop_gogo;if( car_static == stop_brake ){brake_car() ;PWMDTY23 = 1281;car_static = stop_nobrake;}else if( car_static == stop_nobrake )PWMDTY23 = 1281;else if( car_static == stop_gogo ){if( ( control < 550 ) && ( control >- 550 ) ) {PWMDTY23 = setspeed - (control) ;} else if( control >= 550 ){control = 550 ;PWMDTY23 = setspeed-control ;} else if( control <= -550 ){control = -550;PWMDTY23 = setspeed-control ;}}}if((go_flag|0x01)==0x03){switch(uc_AD_Data_divmin_F_count){case first:ui_AA += 1;ui_AA_shadow += 1;ui_BB = 0;ui_CC = 0;ui_DD = 0;ui_EE = 0;ui_GG = 0;ui_GG_shadow = 0;if( ui_AA > 500 )ui_AA = 500 ;if( ui_AA_shadow > 500 ) ui_AA_shadow = 500 ;if( see_blackline == 0 )ui_AA_shadow = 0;break;case second:ui_AA = 0;ui_BB += 1;ui_CC = 0;ui_DD = 0;ui_EE = 0;ui_FF = 0;ui_GG = 0;ui_GG_shadow = 0;ui_AA_shadow = 0;if( ui_BB > 500)ui_BB = 500;break;case three:ui_AA = 0;ui_BB = 0;ui_CC = 0;ui_DD += 1;ui_EE = 0;ui_FF = 0;ui_GG = 0;ui_GG_shadow = 0;ui_AA_shadow = 0;if( ui_DD > 500)ui_DD = 500;break;辽宁工程技术大学毕业设计(论文)ui_AA = 0;ui_BB = 0;ui_CC = 0;ui_DD += 1;ui_EE = 0;ui_FF = 0;ui_GG = 0;ui_GG_shadow = 0;ui_AA_shadow = 0;if( ui_DD > 500)ui_DD = 500;break;case fifth:ui_AA = 0;ui_BB = 0;ui_CC = 0;ui_DD += 1;ui_EE = 0;ui_FF = 0;ui_GG = 0;ui_GG_shadow = 0;ui_AA_shadow = 0;if( ui_DD > 500)ui_DD = 500;break;case sixth:ui_AA = 0;ui_BB = 0;ui_CC = 0;ui_DD = 0;ui_EE = 0;ui_FF += 1;ui_GG = 0;ui_GG_shadow = 0;ui_AA_shadow = 0;if( ui_FF >= 500 )break;case seventh:ui_AA = 0;ui_BB = 0;ui_CC = 0;ui_DD = 0;ui_EE = 0;ui_FF = 0;ui_GG += 1;ui_GG_shadow += 1;ui_AA_shadow = 0;if( ui_GG > 500 )ui_GG = 500 ;if( ui_GG_shadow > 500 )ui_GG_shadow = 500 ;if( see_blackline == 0 )ui_GG_shadow = 0;break;}//++++++++++++++++++++++++++++++++++++++++++if( ui_DD > 100 )uc_road_static = islineroad;else if( ui_DD > 50)uc_road_static = isnearlineroad;//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ if( ( ui_BB >= 5 ) || ( ui_FF >= 5 ) ) //8uc_road_static = islittlebig;else if (( ui_BB >= 1 ) || ( ui_FF >= 1 ) )uc_road_static = isgotobig;//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ if( ( ui_AA >= 10 ) || ( ui_GG >= 10 ) ){if( ( ui_AA_shadow >= 50 ) || ( ui_GG_shadow >= 50 ) )uc_road_static = isgooutroadbig;else if( ( ui_AA_shadow >= 15 ) || ( ui_GG_shadow >= 15 ) )辽宁工程技术大学毕业设计(论文)else if( ( ui_AA >= 2 ) || ( ui_GG >= 2 ) )uc_road_static = isbigturnroad;}else if( ( ui_AA >= 1 ) || ( ui_GG >= 1 ) )uc_road_static = isbigturnroad;go_flag=go_flag&0x01;}if( see_blackline > 50 ){Vf=((AD_Data[uc_AD_Data_divmin_F_count]-AD_Data_min[uc_AD_Data_divmin_F_count])*100)/ee_AD _Data[uc_AD_Data_divmin_F_count];if( Vf> 95 ){if( uc_road_static > 3 ){if( uc_AD_Data_divmin_F_count > 3 ){uc_AD_Data_divmin_F_count = 6;uc_AD_Data_divmin_S_count = 6;}else{uc_AD_Data_divmin_F_count = 0;uc_AD_Data_divmin_S_count = 0;}uc_road_static = isgooutroadbig ;PORTB=0;}}}//*************路线处理****************************************************Vf=((AD_Data[uc_AD_Data_divmin_F_count]-AD_Data_min[uc_AD_Data_divmin_F_count])*100)/ee_AD _Data[uc_AD_Data_divmin_F_count];Vs=((AD_Data[uc_AD_Data_divmin_S_count]-AD_Data_min[uc_AD_Data_divmin_S_count])*100)/ee_AD _Data[uc_AD_Data_divmin_S_count];if( uc_AD_Data_divmin_F_count < uc_AD_Data_divmin_S_count )i_Position=( Position[uc_AD_Data_divmin_S_count]+Position[uc_AD_Data_divmin_F_count] )/2+(((int)(Vf *Position_R[uc_AD_Data_divmin_F_count]-Vs*Position_R[uc_AD_Data_divmin_S_count])/17)/10);i_Position=( Position[uc_AD_Data_divmin_S_count]+Position[uc_AD_Data_divmin_F_count] )/2+(((int)(Vs *Position_R[uc_AD_Data_divmin_S_count]-Vf*Position_R[uc_AD_Data_divmin_F_count])/17)/10);if( uc_AD_Data_divmin_F_count == 0 && Vs > 80 )i_Position = Position[0] - Vf* Position_R[0] / 80;else if( uc_AD_Data_divmin_F_count == 6 && Vs > 80 )i_Position = Position[6] + Vf* Position_R[6] / 80;if( Vf > 60 && Vs > 60 ){if( uc_AD_Data_divmin_F_count == 0 )i_Position = -500 ;if( uc_AD_Data_divmin_F_count == 6 )i_Position = 500 ;}switch( uc_AD_Data_divmin_F_count ){case 0: if( abs(i_Position+460) > 150 )i_Position = -460;break;case 1: if( abs(i_Position+300) > 150 )i_Position = -300;break;case 2: if( abs(i_Position+150) > 150 )i_Position = -150;break;case 3: if( abs(i_Position) > 150 )i_Position = 0;break;case 4: if( abs(i_Position-150) > 150 )i_Position = 150;break;case 5: if( abs(i_Position-300) > 150 )i_Position = 300;break;case 6: if( abs(i_Position-460) > 150 )i_Position = 460;break;}switch(uc_road_static){case isnearlineroad:辽宁工程技术大学毕业设计(论文)PORTA =0xff;PORTA_BIT0=0;if( uc_oldroad_static == isbigturnroad )PD_Proportion=7;elsePD_Proportion=6;SetPoint = Point_nearlineroad;break;case islineroad:PORTA =0xff;PORTA_BIT1 = 0;PD_Proportion=5;uc_oldroad_static = islineroad ;SetPoint = Point_lineroad; //直道速度break;case isbigturnroad:PORTA =0xff;PORTA_BIT2=0;PD_Proportion=9;if( uc_oldroad_static == islineroad ){ //前一个状态是直道的情况/* if( Average_inCatime <= 400) //直道进入弯道速度很快的时候的处理car_static = stop_brake;else */if( Average_inCatime <= 550 )car_static = stop_nobrake;else{car_static = stop_gogo ;SetPoint = Point_bigturnroad ;uc_oldroad_static = isbigturnroad ;}}elseSetPoint = Point_bigturnroad;if( Average_inCatime <= 600 ){if( uc_AD_Data_divmin_F_count == first )i_Position = -500;else if( uc_AD_Data_divmin_F_count == seventh )i_Position = 500;}break;case isgooutroadlittle: //速度降低,舵机摆角不刹车PORTA =0xff;PORTA_BIT3=0;PD_Proportion=9;if( uc_oldroad_static == islineroad ){ //前一个状态是直道的情况/* if( Average_inCatime <= 400) //直道进入弯道速度很快的时候的处理car_static = stop_brake;else */if( Average_inCatime <= 600 )car_static = stop_nobrake;else{car_static = stop_gogo;SetPoint = Point_gooutroadlittle ;uc_oldroad_static=isbigturnroad;}}else{if( Average_inCatime <= 600 )car_static = stop_nobrake;elsecar_static = stop_gogo;SetPoint = Point_gooutroadlittle ;uc_oldroad_static = isbigturnroad;}if( Average_inCatime >= 750 ){if( uc_AD_Data_divmin_F_count == first )辽宁工程技术大学毕业设计(论文)i_Position = -460;else if( uc_AD_Data_divmin_F_count == seventh )i_Position = 460;}else{if( uc_AD_Data_divmin_F_count == first )i_Position = -500;else if( uc_AD_Data_divmin_F_count == seventh )i_Position = 500;}break;case isgooutroadbig:PORTA =0xff;PORTA_BIT4=0;PD_Proportion=9;if( uc_oldroad_static == islineroad ){ //前一个状态是直道的情况/* if( Average_inCatime <= 400) //直道进入弯道速度很快的时候的处理car_static = stop_brake;else */if( Average_inCatime <=600 )car_static = stop_nobrake;else{car_static = stop_gogo;SetPoint = Point_gooutroadbig ;uc_oldroad_static=isbigturnroad;}}else{if( Average_inCatime <= 600 )car_static = stop_nobrake;elsecar_static = stop_gogo;SetPoint= Point_gooutroadbig ;uc_oldroad_static = isgooutroadbig;}if( Average_inCatime >= 750 ){if( uc_AD_Data_divmin_F_count == first )i_Position = -460;else if( uc_AD_Data_divmin_F_count == seventh ) i_Position = 460;}else{if( uc_AD_Data_divmin_F_count == first )i_Position = -500;else if( uc_AD_Data_divmin_F_count == seventh ) i_Position = 500;}break;case islittlebig :PORTA =0xff;PORTA_BIT5=0;if( uc_oldroad_static == islineroad ){SetPoint = Point_littlebig ;PD_Proportion=7;}uc_oldroad_static = isbigturnroad;break;case isgotobig :SetPoint = Point_littlebig ;PD_Proportion=8;uc_oldroad_static = isbigturnroad;}PD_i_Position =i_Position;}。

飞思卡尔程序

飞思卡尔程序
#include <hidef.h> /* common defines and macros */ #include <MC9S12XS128.h> /* derivative information */ #pragma LINK_INFO DERIVATIVE "mc9s12xs128" #pragma MESSAGE DISABLE C12056 /*屏蔽掉这个信息
I
全国大学生智能汽车竞赛
5420,5180,4920,4650,4390,4130,3870,3620,3370,3110,2840}; unsigned char Rev_High[15] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; unsigned int timer_count = 0; int now_position = 0; int last_position = 0; const char Mid_PointWeight[15] = {2,4,68,10,12,14,16,18,20,22,24,26,28,30}; const unsigned char Laser_Ctrl[16] = {0X44,0X41,0X40,0X15,0X14,0X10,0X05,0X04, 0X01,0X00,0X45,0X50,0X51,0X54,0X55,0X11}; unsigned char Out_flag = 0; unsigned char Scan_flag = 0; unsigned char Delay_flag = 0; unsigned char Rev_HighTemp[15][10] = { 0 }; uchar HighP = 0; uchar HighD = 0; uchar MotorP = 0; uchar MotorI = 0; uchar MotorD = 0; int Save_Position[20]; char Load_Position[20]; uint Now_Speed = 0; uint Last_motor_ctrl = 0; uchar Lcd_tableP[] = "P765432101234567"; uchar Lcd_tableD[] = "D000000000000000"; void INIT_REGISTER(void) { /****************锁相环升频 SetBusCLK_40M**********************/ CLKSEL=0X00; //disengage PLL to system PLLCTL_PLLON=1; //turn on PLL SYNR=0X80|0X09; //pllclock=2*osc*(1+SYNR)/(1+REFDV)=160MHz; REFDV=0X80|0X01; //BUS CLOCK=40M POSTDIV=0X01; _asm(nop); _asm(nop); while(!(CRGFLG_LOCK==1)); //when pll is steady ,then use it; CLKSEL_PLLSEL =1; /*********************INIT_I/O********************************/ DDRB = 0XFF; //输出

飞思卡尔光电编码器测速程序

飞思卡尔光电编码器测速程序
/* please make sure that you never leave this function */
}
#pragma CODE_SEG __NEAR_SEG NON_BANKED
void interrupt 68 timer2(void)
{
_asm(MOVB #$07,PITTF); //clear interrupt falg
void delay_ms(uint ms)
{
volatile uint x=0;
while(ms--)
{
for(x=2800;x>0;x--)
{
_asm(nop);
_asm(nop);
_asm(nop);
_asm(nop);
_asm(nop);
_asm(nop);
}
}
}
//注意外接16M晶体。
//飞思卡尔推荐配置,主频道50MHZ,速度更快!
PITCFLMT|=0X80;
//time-out period = (PITMTLD + 1) * (PITLD + 1) / fBUS.
//For example, for a 50 MHz bus clock, the maximum time-out period equals:
//256 * 65536 * 20 ns = 419.43 ms.
_asm(nop);
while(!(CRGFLG_LOCK==1));//when pll is steady ,then use it;
CLKSEL_PLLSEL = 1;//engage PLL to system;
}
//500us one interrupt

飞思卡尔智能车光电组技术报告

飞思卡尔智能车光电组技术报告

第十届全国大学生“飞思卡尔”杯华北赛智能汽车竞赛技术报告目录 (1)第一章方案设计 (1)1.1系统总体方案的选定 (1)1.2系统总体方案的设计 (1)1.3小结 (2)第二章智能汽车机械结构调整与优化 (3)2.1智能汽车车体机械建模 (3)2.2智能汽车传感器的安装 (4)2.2.1速度传感器的安装 (4)222线形CCD 的安装2.2.3车模倾角传感器3.4液晶屏 3.5小结 (12)第四章智能汽车控制软件设计 (13)4.1线性CCD 传感器路径精确识别技术 .......................................... 13 2.3.1电路板的安装 ................... (6)2.3.2电池安放 ........................ (6)2.4其他机械结构的调整 .................... .......62.5小结 .................................. .. (6)第三章智能汽车硬件电路设计 ............... .. (7)3.1主控板设计 ............................ .. (7)3.1.1电源管理模块 ................... . (7)3.1.2电机驱动模块 .................... (8)3.1.3接口模块 ........................ . (9)3.2智能汽车传感器 ........................ (1)3.2.1线性CCD 传感器 .................. . (10)3.2.2陀螺仪 .......................... (1)3.2.3加速度传感器 .................... ............ 错误!未定义书签。

第五届飞思卡尔电磁组原程序——整体

第五届飞思卡尔电磁组原程序——整体
unsigned short* MotorPWM, unsigned short* SteerPWM
)
{ SensorCount=11;
sudu=Speed;
ch_0=SensorData[0];
ch_1=SensorData[1];
ch_2=SensorData[2];
int Ki; //积分常数 Integral Const
int Kd; //微分常数 Derivative Const
int LastError; //Error[-1]
int PrevError; //Error[-2]
flag8=0; f8=0;
}
if(ch_9<255){
flag9=1900;f9=1;
}
if(ch_9>=255){
flag9=0; f9=0;
}
if(ch_10<255){
flag10=21;f10=1;
}
if(ch_10>=255){
flag10=0; f10=0;
int flag0,flag1,flag2,flag3,flag4,flag5,flag6,flag7,flag8,flag9,flag10,Flagstart;
unsigned char Jump=0,Jump0=0,Jump1=0,Jump2=0,Jump3=0,Jump4=0,Jump5=0,Jump6=0,Jump7=0,Jump8=0,Jump9=0;
#include <math.h>
#include "stdafx.h"
#include "控制策略car.h"

飞思卡尔单片机各种功能程序

飞思卡尔单片机各种功能程序

流水灯四种效果:#include <hidef.h> /* common defines and macros */ #include <stdlib.h>#include <mc9s12xdp512.h> /* derivative information */ #pragma LINK_INFO DERIV ATIVE "mc9s12xdp512"#include "main_asm.h" /* interface to the assembly module */ unsigned char temp;//unsigned char pa @0x200;//unsigned char pb @0x202;unsigned char key;static void delay(void) {volatile unsigned long i;for(i=0;i<100000;i++);}static unsigned char random;static void Random(void) {random = (unsigned char)rand();}void effect1() {unsigned char c;for(c=0;c<=6;c++) {delay();PORTB = ~(1<<c);}for(c=7;c>=1;c--) {delay();PORTB = ~(1<<c);}}void effect2() {unsigned char c;for(c=0;c<=6;c++) {delay();PORTB = ~(3<<c);}for(c=7;c>=1;c--) {delay();PORTB = ~(3<<c);}}void effect3() {unsigned char c,t=0xfe;for(c=0;c<=7;c++) {PORTB = t;delay();t<<=1;}}void effect4() {unsigned char c,t=0;for(c=0;c<=7;c++) {PORTB=t;delay();t = (t<<1)+1;;}}void main(void) {unsigned char x;DDRA=0xf0;DDRB=0xff;for(;;) {x=PORTA&0x03;switch(x) {case 0:effect1(); break;case 1:effect2(); break;case 2:effect3(); break;case 3:effect4(); break;}}/* wait forever *//* please make sure that you never leave this function */ }//行列反转法unsigned char key_scan() //键盘扫描函数{ unsigned char x,row=4,col=4,key=16;PUCR|=0x01; //等同于PUCR=PUCR|0x01,PUCR寄存器的第0位设置为1,即允许PORTA端口的上拉电阻。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

}
void setspeed1() {
int idealspeed=7600; static int speedpwm=950; static error_sp=0,errorlast_sp=0,errord_sp=0,errordlast_sp=0,errordd_sp=0; int realspeed; realspeed=sudu; //实际速度 error_sp=idealspeed-realspeed; //当前误差 计算积分项I errord_sp=error_sp-errorlast_sp; //计算比例项P errordd_sp=errord_sp-errordlast_sp; //计算微分项D errorlast_sp=error_sp; //前一次误差 errordlast_sp=errord_sp; //前两次误差
/////////////////////锁相环设置////////////////////////////// int base_Pll_init(void){ CPMUCLKS=0x00; CPMUSYNR=0x00 | 0x02; CPMUREFDIV=0x80 | 0x01; CPMUPOSTDIV=0x00; CPMUOSC_OSCE=1; while(!(CPMUFLG_LOCK==1)); CPMUCLKS_PLLSEL=1; _DISABLE_COP(); EnableInterrupts; } ///////////////////////pulse初始化////////////////////////////
base_Pwm_set(PWM_CHANNEL0,1200,1200); base_Pwm_set(PWM_CHANNEL2,1200,speed);
} int core_Car_speed_close(){ base_Pwm_set(PWM_CHANNEL0,0,0); base_Pwm_set(PWM_CHANNEL2,0,0); } /////////////////////////方向设置///////////////////////// int core_Car_direction_set(int size){ if(size>=0){ base_Pwm_set(PWM_CHANNEL3,10000,9250+250*size/45); } else{ base_Pwm_set(PWM_CHANNEL3,10000,9250-250*abs(size)/45); } }
DDRB=0XFF; DDRD=0X00; DDRC=0X00; EnableInterrupts; base_Init();
core_Car_speed_set(750);
for(;;) { turn();
}
_FEED_COP(); }
///////////////////////定时测脉冲///////////////////////////// void Time0_Init() { TIOS=0x01; //定时器通道0设置为输出比较 TC0=100000; //赋初值,当TCNT从0计数到此值时第一次进入中断 TCTL2=0x01; TSCR2=0x07; //计一个数用5.33微秒 TSCR1=0x80; TIE=0x01; } //中断: #pragma CODE_SEG __NEAR_SEG NON_BANKED interrupt 8 TIM0(void) { TFLG1_C0F=1;//清中断标志位 TIE=0x00; TC0=100000; sudu=PACNT ; //读取脉冲数 //setspeed(); PACNT =0; TIE=0x01;
} } //////////////////////////速度设置/////////////////////////////////// int core_car_speed_setting=0; int core_Car_speed_start(){ base_Pwm_set(PWM_CHANNEL0,1200,1200); base_Pwm_set(PWM_CHANNEL2,1200,1200); } int core_Car_speed_set(int speed){
int idealspeed=17750; static int speedpwm=700; static error_sp=0,errorlast_sp=0,errord_sp=0,errordlast_sp=0,errordd_sp=0; int realspeed; realspeed=sudu; //实际速度 error_sp=idealspeed-realspeed; //当前误差 计算积分项I errord_sp=error_sp-errorlast_sp; //计算比例项P errordd_sp=errord_sp-errordlast_sp; //计算微分项D errorlast_sp=error_sp; //前一次误差 errordlast_sp=errord_sp; //前两次误差
int base_Pulse_count_init() { PACTL=0x50; PACNT = 0x0000; //清0计数器 } //////////////////////////////pwm设置////////////////////////////// int base_Pwm_init(void) { PWME=0x00; PWMCLK=0xff; PWMPRCLK=0x30; PWMSCLA=0x01; PWMSCLB=0x03; PWMPOL=0x00; PWMCAE=0x00; PWMCTL=0xf0; } int base_Pwm_set(Pwm_Channel pchannel,int pper,int pdty){ int *bpwm=(int*)0x00ac; uchar p_start=0x01; p_start = ~(p_start<<(pchannel*2+1)); //PWME &=p_start; bpwm+=pchannel; //*bpwm=0x0000; bpwm+=4; *bpwm=pper; bpwm+=4; *bpwm=pdty; if(pper!=0){ p_start=0x01; p_start=p_start<<(pchannel*2+1); PWME |=p_start;
} #pragma CODE_SEG DEFAULT ///////////////////////////////////////////////////////////
////////////////////////初始化///////////////////////////// void base_Init(void) { base_Pll_init(); base_Pwm_init(); base_Pulse_count_init(); Time0_Init(); }
void sleep(int ms) { int i,j; for(i=0;i<ms;i++) for(j=0;j<2003;j++) {} } ////////////////////////////调整速度PID/////////////////////////// void setspeed() {
///////////////////////////PID变量定义////////////////////// typedef struct { char sp_p; char sp_d; char sp_i; }sp_pid; sp_pid pid={11,3,42}; /////////////////////////////主函数////////////////////////////////// void main(void) {
}
//////////////////////激光头点亮 流水灯///////////////////// void light()
{ PORTB=0x00; sleep(1); dushu4=PORTD_PD4; dushu9=PORTC_PC0; PORTB=0x11; sleep(1); dushu4=PORTD_PD4; dushu1=PORTD_PD1; PORTB=0x22; sleep(1); dushu5=PORTD_PD5; dushu2=PORTD_PD2; PORTB=0x33; sleep(1); dushu5=PORTD_PD5; dushu2=PORTD_PD2; PORTB=0x44; sleep(1); dushu6=PORTD_PD6; dushu3=PORTD_PD3; PORTB=0x55; sleep(1); dushu6=PORTD_PD6; dushu3=PORTD_PD3; PORTB=0x66; sleep(1); dushu7=PORTD_PD7; dushu8=PORTD_PD0; } ///////////////////////////转弯判断////////////////////////////
////////////////////////////函数声明/////////////////////// void base_Init(void); void sleep(int ms); void Time0_Init(); void setspeed(); void light(); void turn(); void CarControl(float measure); void setspeed1(); ////////////////////////////变量定义//////////////////////////////// int k,sudu; int jiaodu=0; int m=0,i=0; int dushu6,dushu5,dushu4,dushu3,dushu2,dushu1,dushu7,dushu8,dushu9; float l_ser_error = 0; float p_ser_error = 0; float n_ser_error = 0; float set_ser = 0; float inc_ser ; float servo_kp; // e(t - 1) // e(t - 2) // e(t)
相关文档
最新文档