main() { setup_ccp1(CCP_COMPARE_CLR_ON_MATCH); // Configure CCP1 in COMPARE mode setup_timer_1(T1_INTERNAL); // Set up timer to instruction clk while(TRUE) { while(input(PIN_B0)) ; // Wait for keypress setup_ccp1(CCP_COMPARE_SET_ON_MATCH); // Configure CCP1 to set CCP_1=0; // C2 high now set_timer1(0); CCP_1 = 500; // Set high time limit // to 100 us // limit is time/(clock/4) // 500 = .0001*(20000000/4) setup_ccp1(CCP_COMPARE_CLR_ON_MATCH); // Configure CCP1 in COMPARE // mode and to pull pin C2 // low on a match with timer1 delay_ms(1000); // Debounce - Permit only one pulse/sec } }
void pwm_init (int1 enabled) { set_tris_c (0); /* CCP1 is RC2, CCP2 is RC1 */ pwm_enabled = enabled; if (enabled) { setup_ccp1 (CCP_PWM); setup_ccp2 (CCP_PWM); setup_timer_2 (T2_DIV_BY_16, 255, 1); // 88 is 2.8 KHz } else { setup_ccp1 (CCP_OFF); setup_ccp2 (CCP_OFF); } }
void main() { enable_interrupts(INT_CCP1); enable_interrupts(global); setup_timer_1(T1_INTERNAL|T1_DIV_BY_1); setup_ccp1(CCP_COMPARE_SET_ON_MATCH); set_timer1(500); ccp_1=40000; while(1); }
/*======================= configuracon de dispositivos =======================*/ void setup_devices(){ //int myerror = 0; /*========================= configuracion del USB =========================*/ myerror = COM_init(); /*========================= configuracion del MMA7455 =====================*/ //myerror += MEMORIA_init_hw(); //myerror += MEMORIA_init(); /*========================= conversor analogo/digital =====================*/ // myerror = AD_init_adc(); /*========================= modulo CPP ====================================*/ //myerror = CP_init_ccp(); /*========================= configuracion del Reloj Digital ===============*/ //ds1307_init(DS1307_OUT_ON_DISABLED_HIHG | DS1307_OUT_ENABLED | DS1307_OUT_1_HZ); //ds1307_set_date_time(0x0d, 0x01, 0x0d, 0x00, 0x0a, 0x2a, 0x00); /*-------------------------------------------------------------------------*/ setup_psp(PSP_DISABLED); setup_wdt(WDT_OFF); setup_timer_0(RTCC_INTERNAL); setup_timer_1(T1_DISABLED); setup_timer_2(T2_DISABLED,0,1); setup_comparator(NC_NC_NC_NC); setup_vref(FALSE); #ifndef CAPTURA_FRECUENCIA_H setup_timer_3(T3_DISABLED|T3_DIV_BY_1); setup_ccp1(CCP_OFF); #endif /*-------------------------------------------------------------------------*/ /*===================para los indicadores========================*/ set_tris_e(0x00); set_tris_b(0x00); set_tris_c(0x80); //configuracion para el modulo de memoria set_tris_d(0x48); output_bit(INDICADOR_USB, 0); output_bit(INDICADOR_AMARILLO, 1); //////////////////////////////// output_low(SPI_SCL); output_high(SPI_SS); output_low(SPI_MOSI); output_high(SPI_MISO); //////////////////////////////// //delay_ms(3000); /*===============================================================*/ return; }
void main() { setup_timer_2(T2_DIV_BY_16,255,1); //4.0 ms overflow, 4.0 ms interrupt setup_ccp1(CCP_PWM); setup_ccp2(CCP_PWM); set_pwm1_duty((int16)200); set_pwm2_duty((int16)200); enable_interrupts(INT_SSP); enable_interrupts(GLOBAL); SET_TRIS_B(0); stop(); //delay_ms(500); while(TRUE) { if(hasCommand) { hasCommand= FALSE; if(buffer[0] == 's'){ show(); } else switch(buffer[1]) { case 1: go_forward(); break; case 2: go_backward(); break; case 3: turn_right(); break; case 4: turn_left(); break; case 5: stop(); break; default : break; } } } }
void setup_motors() //initialize PWM { //setup_timer_2(T2_DIV_BY_1, 255, 16); setup_timer_2(T2_DIV_BY_16, SPEED, 16); //setup_timer_2(T2_DIV_BY_4, 63, 16); // 5Mz instruction cycle, pwm cycle every 4*64 cycles (19.5khz) // interrupt every 16th of that (not used) setup_ccp1(CCP_PWM); // PWM output on CCP1/RC2, pin 17 setup_ccp2(CCP_PWM); // PWM output on CCP2/RC1, pin 16. PWM2 can be moved to pin 36; see ServoSkeleton }
main() { printf("\r\nHigh time (sampled every second):\r\n"); setup_ccp1(CCP_CAPTURE_RE); // Configure CCP1 to capture rise setup_ccp2(CCP_CAPTURE_FE); // Configure CCP2 to capture fall setup_timer_1(T1_INTERNAL); // Start timer 1 enable_interrupts(INT_CCP2); // Setup interrupt on falling edge enable_interrupts(GLOBAL); while(TRUE) { delay_ms(1000); printf("\r%lu us ", pulse_width/5 ); } }
//**** Funciones genericas *************************************************** void Inicio(void){ //--- ini: mPaP ----------------------------------------------------------- numPulsosX=numPulsosY=numPulsosZ=numPulsosE=0; periodoPulsosX=periodoPulsosY=periodoPulsosZ=periodoPulsosE=0; //--- ini: PID ------------------------------------------------------------ min=0.0; max=1023 ; //valor Anti-windup i1=0;e1=0;d1=0; Kd=8; Kp=8; Ki=0.02915; T=5; //Tiempo de muestreo tr/6 < T < tr/20 Kpz=Kp; Kiz=Ki*T/2; Kdz=Kd/T; //--- ini: CCP --------------------------------------------------------- //--- Pre=16 PR2=249 Pos=1, PWMF=3kHz,PWMT=300us con Fosc(clock)=48MHz setup_timer_2(T2_DIV_BY_16,249,1); setup_ccp1(ccp_pwm); //Configurar modulo CCP1 en modo PWM set_pwm1_duty(0); //--- ini: ADC --------------------------------------------------------- setup_adc_ports(AN0|VSS_VDD ); setup_adc(ADC_CLOCK_INTERNAL); //setup_adc(ADC_CLOCK_DIV_8); //respetar el Tad>1.6us //Tad=8/Fosc=8/20Mhz=400ns set_adc_channel(0); //Seleccionar Canal(0)=AN0=A0 para ADC //--- ini: TIMER0 for OS_Timer() --------------------------------------- setup_timer_0(RTCC_INTERNAL|RTCC_DIV_1); //config Timer0, Pre=1=RTCC_DIV_1 //set_timer0(0xF63B); //carga del Timer0, clock=20MHz, Fout=1kHz=0xF63B set_timer0(0xE88F); //carga del Timer0, clock=48MHz, Fout=1kHz=0xE88F //--- ini: Interrupts -------------------------------------------------- //enable_interrupts(GLOBAL); enable_interrupts(INT_TIMER0); //habilita interrupcion Timer0 //enable_interrupts(INT_TIMER2); //--- ini: USB ------------------------------------------------------------ usb_init(); //inicializamos el USB usb_task(); //habilita periferico usb e interrupciones usb_wait_for_enumeration(); //esperamos hasta que el PicUSB //sea configurado por el host delay_ms(50); }
//Incluye las cabeceras antes descritas void main(){ //Rutina principal output_high(LED); //Enciende el LED indicador lcd_init(); //Rutina de incializacion del LCD lcd_putc("\fListo \n"); //Despliega el mensaje "Listo" en el LCD setup_adc_ports(AN0); //Fija el pin 0 del puerto A como entrada analogica setup_adc (adc_clock_internal); //El tiempo para la conversion AD esta dado por el oscilador //interno set_adc_channel(0); //El puerto AD activo es el 0 enable_interrupts(INT_EXT); //Habilita la interrupcion externa en RB0 ext_int_edge(L_to_H); //Fija la interrupcion por flanco de subida. setup_timer_2(T2_DIV_BY_16,129,16); //El tiempo de oscilacion del timer 2 sirve tanto para la //interrupcion por timer2 como para el PWM. setup_ccp1(CCP_PWM); //Da de alta el modulo CCP1 como PWM //y lo inicializa en duty cycle 0 set_pwm1_duty(0); setup_ccp2(CCP_PWM); //Da de alta el modulo CCP2 como PWM //y lo inicializa en duty cycle 0 set_pwm2_duty(0); enable_interrupts(GLOBAL); //Habilita las interrupciones globales output_low(LED); //Apaga el led antes encendido. while(TRUE){ //Esta rutina espera a la interrupcion y parpadea el LED //indicador output_low(LED); delay_ms(100); output_high(LED); delay_ms(100); } }
void main() { int i, seq[10] = {n0, n1, n2, n3, n4, n5, n6, n7, n8, n9}, tensao; setup_adc_ports(AN0|VSS_VDD); setup_adc(ADC_CLOCK_DIV_8); setup_psp(PSP_DISABLED); setup_spi(SPI_SS_DISABLED); setup_wdt(WDT_OFF); setup_timer_0(RTCC_INTERNAL); setup_timer_1(T1_DISABLED); setup_timer_2(T2_DISABLED,0,1); setup_ccp1(CCP_OFF); setup_comparator(NC_NC_NC_NC); setup_vref(FALSE); set_adc_channel(0); //TODO: User Code while(TRUE) { tensao = read_adc(); if(tensao >= 127) { for(i = 1; i < 10; i++) { output_D(seq[i]); delay_ms(1000); } } else { for(i = 9; i >= 1; i--) { output_D(seq[i]); delay_ms(1000); } } } }
void main() { setup_timer_0 (RTCC_INTERNAL|RTCC_DIV_256); setup_timer_1 (T1_INTERNAL|T1_DIV_BY_8); setup_timer_2(T2_DIV_BY_16,155,1); setup_ccp1(CCP_PWM); set_pwm1_duty(0); setup_comparator(NC_NC_NC_NC); setup_vref(FALSE); enable_interrupts (int_TIMER1); enable_interrupts (GLOBAL); config (); while (true) { if (ReceberComando ()==1) { output_toggle (led) ; verificaComando (cmd[2]); } } }
void init() { unsigned int16 i; blink(); init_queue(&rxque0); init_queue(&txque0); set_step(1); // 0=full, 1=1/2, 5=1/4, 4=1/8, 7=1/16 enable(1); //setup_counters(T0_INTERNAL, T0_DIV_1 | T0_8_BIT); setup_counters(T0_INTERNAL, T0_DIV_2 | T0_8_BIT); set_timer0(0); enable_interrupts(INT_RTCC); enable_interrupts(INT_RDA); enable_interrupts(GLOBAL); output_bit(CTS,0); // ready to receive from usb output_bit(STROBE,1); // parallel port strobe // input(PIN_C3); // ESTOP input(PIN_C4); // ALIM input(PIN_C0); // XLIM input(PIN_C1); // YLIM // input(PIN_C2); // ZLIM output_bit(PIN_C2,0); // changed from ZLIM to PWM OUTPUT setup_ccp1(CCP_PWM); setup_timer_2(T2_DIV_BY_16, 255, 1); // mode, period, postscale set_timer2(0); set_pwm1_duty(0); // duty cycle is val/(4*(255+1)) }
void main() { //initialize data var_init(); //initialize timers and cp1 interrupt setup_timer_1(T1_INTERNAL | T1_DIV_BY_2); //div 2 - 26.2 ms overflow setup_ccp1(CCP_CAPTURE_FE); //with 819.2 us overflow for Timer0, motor's speed must be at least 20 RPS setup_timer_0(T0_INTERNAL | T0_DIV_16); //div 16 - 819.2 us overflow //enable interrupts enable_interrupts(INT_RB2|INT_RB3|INT_RB4|INT_RB5);; enable_interrupts(INT_EXT); enable_interrupts(INT_TIMER1); enable_interrupts(INT_CCP1); enable_interrupts(INT_TIMER0); enable_interrupts(INT_RDA); enable_interrupts(GLOBAL); //initialize clock ds1307_init(); //test power on rgb_bits.blue = 0xF00F; rgb_bits.red = 0x0F0F; rgb_bits.green = 0x00FF; latch_write(rgb_bits.blue, rgb_bits.red, rgb_bits.green); //get the first values of date, time ds1307_get_time(hour, min, sec); ds1307_get_date(day, month, year, dow); // calculating hour hand's position for analog clock anal_hour = hour % 12; anal_hour = anal_hour * 5; anal_hour = anal_hour + (int8)(min / 12); // calculating hour, minute, day, month numbers to display in digital clock hour_h = (int8)(hour / 10); hour_l = hour % 10; min_h = (int8)(min / 10); min_l = min % 10; day_h = (int8)(day / 10); day_l = day % 10; month_h = (int8)(month / 10); month_l = month % 10; // main routine while(true) { // rs232 operation if (rs232_status == 11) { //notify the RS232 transmission for date, time update is successful latch_write(0x0000, 0x0FF0, 0x0000); rs232_status = 0; ds1307_set_date_time(day, month, year, dow, hour, min, sec); putc('O'); delay_ms(100); putc('K'); delay_ms(100); latch_ClearAll(); } // get the time value from ds1307 after each 5 minutes if(tick == 300) { ds1307_get_time(hour, min, sec); ds1307_get_date(day, month, year, dow); anal_hour = hour % 12; anal_hour = anal_hour * 5; anal_hour = anal_hour + (int8)(min / 12); tick = 1; } // change values of minute and hour at appropriate value of second and minute if(sec > 59) { sec = 0; min++; if(min > 59) { min = 0; ds1307_get_time(hour, min, sec); anal_hour = hour % 12; anal_hour = anal_hour * 5; anal_hour = anal_hour + (int8)(min / 12); } //refresh value for digital clock after each minute hour_h = (int8)(hour / 10); hour_l = hour % 10; min_h = (int8)(min / 10); min_l = min % 10; } //display routine if(circle_trigger == 1) { circle_trigger = 0; if ((smode % 2) == 1) latch_ClearAll(); digit_sec++; section_trigger = 1; section_count = MAX_SECTION; section_timer = 256 - (int8)(sigHall_timer / (MAX_SECTION * 8)) + tuning; while(circle_trigger == 0 && section_count > 0) { if(section_trigger == 1) { set_timer0(section_timer); section_trigger = 0; //data calculation fetch_data(); //shifting data latch_write(rgb_bits.blue, rgb_bits.red, rgb_bits.green); //smode change between continuous display and discrete display if ((smode % 2) == 1 && section_count > 1) latch_ClearAll(); section_count--; } } }// circle_trigger } // end of while(true) }
void main() { char string[30]; char ch; int auxc1,auxcb,auxs; int pilha_can[11]; setup_adc_ports(NO_ANALOGS); setup_adc(ADC_CLOCK_DIV_2); setup_spi(spi_master|spi_h_to_l|spi_clk_div_4|spi_ss_disabled|spi_sample_at_end); setup_timer_0(RTCC_INTERNAL); setup_timer_1(T1_DISABLED); setup_timer_2(T2_DISABLED,0,1); setup_ccp1(CCP_OFF); setup_ccp2(CCP_OFF); enable_interrupts(INT_RDA);//tirar se quiser arrancar em debug disable_interrupts(global); DEBUG=false; #IF CDEBUG DEBUG=true; #ENDIF strcpy(go,"debug"); //START MCP2510*************************************************** f2510rst(); delay_ms(1000); f2510cfg(); delay_ms(1000); auxc1=read_eeprom(save_adr); f2510cfg_end(auxc1,0); //**************************************************************** pilha_rs232[0]=0; pilha_can[0]=0; enable_interrupts(global); while(true) { while(DEBUG==false) { auxs=f2510rx(pilha_can); if (auxs==1) printf("ERROR CAN_BUFFER FULL n\\r"); else if (auxs==0) { printf(":%X%X%X%X%X%X",pilha_can[1],pilha_can[2],pilha_can[3],pilha_can[4],pilha_can[5],pilha_can[6]); for(auxs=0;auxs<pilha_can[6];++auxs) { printf("%X",pilha_can[7+auxs]); } printf("\r"); pilha_can[0]=0; } if(pilha_rs232[0]==1) { auxs=f2510tx(pilha_rs232); if (auxs==false) printf("ERROR TX CAN BUFFER FULL \n\r"); } } while(DEBUG==TRUE) { printf("******************************\n\r"); printf("* 1-Debug OFF *\n\r"); printf("* 2-MCP dump *\n\r"); printf("* 3-MCP config *\n\r"); printf("* 4-MCP Send *\n\r"); printf("* 5-configuracao de end *\n\r"); printf("* 6-MCP reset *\n\r"); printf("* 7-MCP receive *\n\r"); printf("* 8-clear receive buffer *\n\r"); printf("* g-SAVE Adress *\n\r"); printf("* l-READ Adress *\n\r"); printf("******************************\n\r"); ch=getc(); printf("%C\r",ch); switch(ch) { case '1': printf("\n\r DEBUG MODE OFF \n\r"); DEBUG=FALSE; pilha_can[0]=0; pilha_rs232[0]=0; enable_interrupts(INT_RDA); enable_interrupts(global); break; case '2': f2510dump(); break; case '3': f2510cfg(); break; case '4': printf ("\n\r Introduza endereco de destino \n\r"); gets(string); pilha_rs232[1]=atoi(string); printf ("\n\r Introduza sub endereco de destino \n\r"); gets(string); pilha_rs232[2]=atoi(string); printf ("\n\r Introduza endereco de origem \n\r"); gets(string); pilha_rs232[3]=atoi(string); printf ("\n\r Introduza sub endereco de origem \n\r"); gets(string); pilha_rs232[4]=atoi(string); printf ("\n\r Introduza tipo \n\r"); gets(string); pilha_rs232[5]=atoi(string); printf ("\n\r Introduza tamanho dado \n\r"); gets(string); pilha_rs232[6]=atoi(string); for(auxc1=1;auxc1<pilha_rs232[6]+1;++auxc1){ printf ("\n\r Introduza dado %d\n\r",auxc1); gets(string); pilha_rs232[7+auxc1-1]=atoi(string); } auxcb=f2510tx(pilha_rs232); printf ("\n\r resultado = %02x \n\r",auxcb); break; case '5': printf ("\n\r Introduza endereco \n\r"); gets(string); auxc1=atoi(string); f2510cfg_end(auxc1,0); break; case 'g': printf ("\n\r Introduza endereco \n\r"); gets(string); auxc1=atoi(string); write_eeprom(save_adr,auxc1); break; case 'l': auxc1=read_eeprom(save_adr); printf("\n\r Endereco=%u\n\r",auxc1); break; case '6': f2510rst(); break; case '7': printf("\n RESULTADO=%u\n",f2510rx(pilha_can)); printf("\n\r end_dest=%u \n\r",pilha_can[1]); printf("\n\r sub_end_dest=%u \n\r",pilha_can[2]); printf("\n\r end_orig=%u \n\r",pilha_can[3]); printf("\n\r sub_end_orig=%u \n\r",pilha_can[4]); printf("\n\r tipo=%u \n\r",pilha_can[5]); printf("\n\r comp_dados=%u \n\r",pilha_can[6]); for(auxc1=0;auxc1<pilha_can[6];++auxc1) { printf("\n\r dado %u=%u \n\r",auxc1+1,pilha_can[7+auxc1]); } break; case '8': f2510bc(0x2c,0); pilha_can[0]=0; break; } } } }
void main() { setup_adc_ports(NO_ANALOGS); setup_adc(ADC_CLOCK_DIV_2); setup_psp(PSP_DISABLED); setup_spi(SPI_SS_DISABLED); setup_timer_0(RTCC_INTERNAL|RTCC_DIV_1); setup_timer_1(T1_DISABLED); setup_timer_2(T2_DIV_BY_16,155,1); setup_ccp1(CCP_PWM); setup_ccp2(CCP_PWM); set_pwm1_duty(312); // Inicia el Ciclo de Trabajo PWM1 en 50%. set_pwm2_duty(312); // Inicia el Ciclo de Trabajo PWM2 en 50%. setup_comparator(NC_NC_NC_NC); setup_vref(FALSE); set_tris_a(0b11100000); // set_tris_c(0b10000000); //Pone RC7 como input y RC6 como output (y de 5 a 0 también) set_tris_b(0b00000000); // Habilita como salidas los pines B0, B1,...,B7 set_tris_e(0b010); // ************************ CONFIGURACIÓN PWM1 y PWM2: ************************ int32 brillo=0; int32 exposicion=500; //Tiempo de exposición de la cámara en [ms] int32 der_steps=0; int32 izq_steps=0; int32 led=0; int32 motor=0; int32 direccion=0; int32 pasos=0; int32 velocidad=0; char leido_pantalla[5]; output_low(PIN_B0); output_low(PIN_B1); output_low(PIN_B2); output_low(PIN_B3); output_low(PIN_B4); output_high(PIN_B6); // Siempre en 5V para conectar pull up 10kOhm de RA4 para SLEEP MOTOR 3 (altura) set_pwm1_duty(0); // Mantiene Ciclos en 0 para reducir consumo al iniciar. set_pwm2_duty(0); //*************** INICIO *************** while(true) { char seleccionar=0; output_low(PIN_A2); output_low(PIN_A3); output_low(PIN_A4); printf("Set parameters: e=exposicion(%Ld), v=velocidad(%Ld)\n\r",exposicion,velocidad); printf(" b=brillo(%Ld), d=direccion(%Ld), p=pasos(%Ld)\n\r",brillo,direccion,pasos); printf(" l=led(%Ld), m=motores(%Ld) \n\r",led,motor); seleccionar=getc(); switch(seleccionar) { case 'v': printf("Ingrese Velocidad en [ms] y [ENTER]\n\r"); fgets(leido_pantalla); velocidad=atoi32(leido_pantalla); break; case 'e': printf("Ingrese tiempo de exposicion en [ms] y [ENTER]\n\r"); fgets(leido_pantalla); exposicion=atoi32(leido_pantalla); break; case 'b': printf("Ingrese Ciclo de Trabajo para PWM1 (0-100) (brillo) y [ENTER]:\n\r"); fgets(leido_pantalla); brillo=atoi(leido_pantalla); set_pwm1_duty(brillo*20000000/(100*2000*16)); set_pwm2_duty(brillo*20000000/(100*2000*16)); break; case 'l': printf("Ingrese Led a encender: 0 a 7 y [ENTER]\n\r"); fgets(leido_pantalla); led=atoi32(leido_pantalla); break; case 'd': printf("Ingrese direccion 1=Derecha, 0=Izquierda y [ENTER]\n\r"); fgets(leido_pantalla); direccion = atoi32(leido_pantalla); break; case 'p': printf("Ingrese el numero de pasos a utlizar y [ENTER]\n\r"); fgets(leido_pantalla); pasos = atoi32(leido_pantalla); break; case 'm': printf("Ingrese el numero de motor a utlizar: 1,2 o 3 y [ENTER]\n\r"); fgets(leido_pantalla); motor = atoi32(leido_pantalla); break; case '1': led_on(led); break; case '2': led_off(); break; case '3': motor_move(motor,pasos,direccion); break; case '4': led_on_off(led,exposicion); break; case '5': int32 pasos_restantes; int32 steps; int dir; dir = direccion; steps = pasos; pasos_restantes = pasos; motor_on(motor); while(pasos_restantes > 0){ printf("pasos_restantes: %Ld\n\r",pasos_restantes); delay_us(200); steps = motores4(pasos_restantes,dir,velocidad); pasos_restantes = pasos_restantes - steps; if (pasos_restantes <=0) break; delay_us(200); dir = (dir == 0)?1:0; motores2(2000,dir); } break; case '6': int32 pasos_restantes2; int32 steps2; int dir2; dir2 = direccion; steps2 = pasos; pasos_restantes2 = pasos; motor_on(motor); while(true){ printf("pasos restantes: %Ld\n\r",pasos_restantes2); delay_us(200); steps2 = motores4(pasos_restantes2,dir2,velocidad); delay_us(200); dir2 = (dir2 == 0)?1:0; motores2(2000,dir2); pasos_restantes2 = pasos_restantes2 - steps2; if (pasos_restantes2 <=0) pasos_restantes2 = pasos; } break; case '7': int32 steps3; motor_on(motor); steps3 = motores4(pasos,direccion,velocidad); if (steps3 - pasos < 0){ direccion = (direccion == 0)?1:0; motores2(2000,direccion); delay_us(200); motores3(2147483640,direccion); direccion = (direccion == 0)?1:0; motores2(2000,direccion); } break; case '8': printf("Setup Calibracion Quick\n\r"); motor_on(motor); motores3(2147483640,DERECHA); delay_us(200); motores2(2000,IZQUIERDA); delay_us(200); izq_steps = motores3(2147483640,IZQUIERDA); delay_us(200); motores2(2000,DERECHA); delay_us(200); der_steps = motores3(2147483640,DERECHA); printf("izq_steps ->%Ld<- \n\r",izq_steps); printf("der_steps ->%Ld<- \n\r",der_steps); while(true){ motores2(izq_steps,IZQUIERDA); delay_us(200); motores2(der_steps,DERECHA); delay_us(200); } case '9': printf("Setup Velocidad ...\n\r"); output_high(PIN_A4); motores2(2000,IZQUIERDA); delay_us(200); izq_steps = motores3(2147483640,IZQUIERDA); delay_us(200); motores2(2000,DERECHA); delay_us(200); der_steps = motores3(2147483640,DERECHA); printf("izq_steps ->%Ld<- \n\r",izq_steps); printf("der_steps ->%Ld<- \n\r",der_steps); motores4(izq_steps,IZQUIERDA,velocidad); delay_us(200); motores4(der_steps,DERECHA,200); delay_us(200); break; } } } //FIN MAIN
main() { char selection; byte value; printf("\r\nFrequency:\r\n"); printf(" 1) 19.5 khz\r\n"); printf(" 2) 4.9 khz\r\n"); printf(" 3) 1.2 khz\r\n"); do { selection=getc(); } while((selection<'1')||(selection>'3')); setup_ccp1(CCP_PWM); // Configure CCP1 as a PWM // The cycle time will be (1/clock)*4*t2div*(period+1) // In this program clock=10000000 and period=127 (below) // For the three possible selections the cycle time is: // (1/10000000)*4*1*128 = 51.2 us or 19.5 khz // (1/10000000)*4*4*128 = 204.8 us or 4.9 khz // (1/10000000)*4*16*128= 819.2 us or 1.2 khz switch(selection) { case '1' : setup_timer_2(T2_DIV_BY_1, 127, 1); break; case '2' : setup_timer_2(T2_DIV_BY_4, 127, 1); break; case '3' : setup_timer_2(T2_DIV_BY_16, 127, 1); break; } setup_port_a(ALL_ANALOG); setup_adc(adc_clock_internal); set_adc_channel( 0 ); printf("%c\r\n",selection); while( TRUE ) { value=read_adc(); printf("%2X\r",value); set_pwm1_duty(value); // This sets the time the pulse is // high each cycle. We use the A/D // input to make a easy demo. // the high time will be: // if value is LONG INT: // value*(1/clock)*t2div // if value is INT: // value*4*(1/clock)*t2div // for example a value of 30 and t2div // of 1 the high time is 12us // WARNING: A value to high or low will // prevent the output from // changing. } }
void main() { int1 flag = 0; porta = 0;//all ports are zero portb = 0; portc = 0; setup_adc_ports(no_analogs|vss_vdd); //digital functions selected setup_adc(adc_off); //internal rc oscillator disabled for adc setup_wdt(wdt_off); //watch dog timer disabled setup_timer_0(rtcc_off); //all timers disabled setup_timer_1(t1_disabled); setup_timer_2(t2_disabled,0,1); setup_timer_3(t3_disabled|t3_div_by_1); setup_comparator(nc_nc_nc_nc); //comparators disabled setup_vref(false); //no reference voltage in ra2 setup_ccp1(ccp_off); //disable ccp1 setup_ccp2(ccp_off); //disable ccp2 enable_interrupts(int_rda); //uart rx interruption enabled enable_interrupts(global); //global interruptions enabled usb_cdc_init(); usb_init(); //initialize hardware usb and wait for PC conection set_tris_a(0b00111111); set_tris_b(0b11111011);//rb2 output mclr dspic port_b_pullups(false); set_tris_c(0b10111111); stateDspic = running; counterReset = 0; delay_ms(500);//wait for supply stabilization while(true) { usb_task(); manage_conection(); if (usb_cdc_kbhit()) { data_rx_usb=usb_cdc_getc();//read buffer and save in data_rx printf("%c",data_rx_usb);//send through uart if (data_rx_usb == rstKeyword[0]) { if (counterReset == 0) counterReset++; } else if (data_rx_usb == rstKeyword[1]) { if (counterReset == 1) counterReset++; else counterReset = 0; } else if (data_rx_usb == rstKeyword[2]) { if (counterReset == 2) counterReset++; else counterReset = 0; } else if (data_rx_usb == rstKeyword[3]) { if (counterReset == 3) counterReset++; else counterReset = 0; } else if (data_rx_usb == rstKeyword[4] && counterReset == 4)//here, all requirements were met { counterReset = 0; flag = 0; //reset flag for(i = 0; i < 10000; i++) //wait for the next byte { if (usb_cdc_kbhit()) //if a new byte is received { data_rx_usb = usb_cdc_getc();//read buffer and save in data_rx printf("%c",data_rx_usb);//send through uart flag = 0; break; } flag = 1; } if (flag == 1) //apply reset when no characters were received { stateDspic = stop; delay_ms(50); stateDspic = running; } } else counterReset = 0; } } }
//programa principal void main() { set_tris_A(0x00);/* 0000 0000 RA0 LED1 PIN 02 RA1 LED2 PIN 03 RA2 LED3 PIN 04 RA3 LED4 PIN 05 RA4 LED5 PIN 06 RA5 LED6 PIN 07 */ set_tris_B(0x00);/* (0000 0000) RB0 LED7 PIN 40 RB1 LED8 PIN 39 RB2 LED9 PIN 38 RB3 LED10 PIN 37 RB4 LED11 PIN 36 RB5 LED12 PIN 35 RB6 LED13 PIN 34 RB7 LED14 PIN 33 */ set_tris_C(0X00);/* RC0 ----- PIN 15 RC1 ----- PIN 16 RC2 ----- PIN 17 RC6 LED15 PIN 25 RC7 LED16 PIN 26 */ // Configuración de Leds 17 hasta 20 y Pulsadores 1 y 2 set_tris_D(0X00);/* RD0 SW01 PIN 19 --->Pulsador 1 RD1 SW02 PIN 20 --->Pulsador 2 RD2 ----- PIN 21 RD3 ----- PIN 22 RD4 LED17 PIN 27 RD5 LED18 PIN 28 RD6 LED19 PIN 29 RD7 LED20 PIN 30 */ set_tris_E(0x00);/* bits(**** 0000) RE0 ----- PIN 08 RE1 ----- PIN 09 RE2 ----- PIN 10 RE3 ----- PIN 01 */ //Habilitando y deshabilitando modulos... setup_timer_1(T1_disabled); setup_timer_2(T2_disabled,0,1); setup_timer_3(T3_disabled); setup_ccp1(CCP_OFF); setup_ADC(ADC_OFF); setup_VREF(FALSE);//no voltaje de referencia setup_COMPARATOR(NO_ANALOGS);// //limpie los puertos OUTPUT_A(0x00); OUTPUT_B(0x00); OUTPUT_C(0X00); OUTPUT_D(0X00); //limpiar registros, probar limpiar todos los registros en assembler con =0 //#ZERO_RAM limpiarRegistros(); /*condicional para lanzar secuencia cuando el pulsador esté presionado. */ output_float(SW01); output_float(SW02); while(TRUE) { if (input_state(SW01) == 1 && input_state(SW02) == 1) { secuencia1(); }else if (input_state(SW01) == 0 && input_state(SW02) == 1) { secuencia2(); }else if (input_state(SW01) == 1 && input_state(SW02) == 0) { secuencia4(); }else { } } //vuelva a inicio y vuelva y arranque reset_cpu(); }
void main() { TRISC=0; // Variables para controlador int16 valor; float control; //valor del PWM float a1,b1,c1; //constantes del PID float ref; //temperatura a alcanzar float rT,eT,iT,dT,yT,uT,iT0,eT0,iT_1,eT_1; //variables de ecuaciones float max,min; //límites máximo y mínimo de control. float T ,Kp1, Ti1,Td1; setup_adc_ports(RA0_ANALOG);//entrada del LM35 setup_adc(ADC_CLOCK_INTERNAL); setup_COUNTERS(RTCC_internal.rtcc_div_1); set_adc_channel(0); setup_timer_2(t2_div_by_4,500,1); //periodo de la señal PWM a 1ms setup_ccp1(ccp_pwm); //Módulo CCP a modo PWM setup_adc(ADC_CLOCK_INTERNAL); //reloj convertidor AD interno set_adc_channel(0); setup_timer_0(rtcc_ext_l_to_h|RTCC_DIV_2); //Configuración TMR0 setup_timer_1(T1_internal|T1_DIV_BY_8); //Configuración TMR1 float Temp; int c; char k; char Kp[6]; char Ki[6]; char Kd[6]; char Sp[6]; int v; port_b_pullups(true), lcd_init(); kbd_init(); inicio: for (v=0;v<=5;v++){ Kp[v]=0; Ki[v]=0; Kd[v]=0; Sp[v]=0; } lcd_gotoxy(1,1); lcd_putc("\f"); lcd_putc("Kp:"); lcd_gotoxy(9,1); lcd_putc("Ki:"); lcd_gotoxy(1,2); lcd_putc("Kd:"); lcd_gotoxy(9,2); lcd_putc("Sp:"); while(true){ K_p: lcd_gotoxy(4,1); lcd_send_byte(0,0x0f); c=0; k=0; while(c<=4){ k=kbd_getc(); if(k!=0){ if(k!='A' && k!='*' && k!='C'){ if(k=='B'){ printf(lcd_putc,"."); Kp[c]=k; lcd_gotoxy(4+c,1); } else printf(lcd_putc,"%c",k); Kp[c]=k; lcd_gotoxy(4+c,1); } if(k=='A'){ c++; Kp[c]=-92; lcd_gotoxy(4+c,1); } } if(k=='D'){ int j=0; for(;;){ Kp[j]=0; if(j==5) break; j++; } c=0; lcd_gotoxy(1,1); lcd_putc("Kp: "); lcd_gotoxy(4+c,1); } if(k=='*'){ Kp[c+1]=-92; goto K_i; } } //FUERA DEL WHILE lcd_gotoxy(4+c-1,1); lcd_send_byte(0,0x0f); k=0; for(;;){ k=kbd_getc(); if(k!=0){ if(k=='*'){ break; } } } K_i: lcd_gotoxy(12,1); lcd_send_byte(0,0x0f); c=0; k=0; ///KI while(c<=4){ k=kbd_getc(); if(k!=0){ if(k!='A' && k!='*'){ if(k=='B'){ printf(lcd_putc,"."); Ki[c]=k; lcd_gotoxy(12+c,1); } else printf(lcd_putc,"%c",k); Ki[c]=k; lcd_gotoxy(12+c,1); } if(k=='A'){ c++; Ki[c]=-92; lcd_gotoxy(12+c,1); } } if(k=='D'){ int j=0; for(;;){ Ki[j]=0; if(j==5) break; j++; } c=0; lcd_gotoxy(9,1); lcd_putc("Ki: "); lcd_gotoxy(12+c,1); } if(k=='*'){ Ki[c+1]=-92; goto K_d; } } ///FIN KI ///FUERA DEL WHILE lcd_gotoxy(12+c-1,1); lcd_send_byte(0,0x0f); k=0; for(;;){ k=kbd_getc(); if(k!=0){ if(k=='*'){ break; } } } K_d: lcd_gotoxy(4,2); lcd_send_byte(0,0x0f); c=0; k=0; while(c<=4){ k=kbd_getc(); if(k!=0){ if(k!='A' && k!='*'){ if(k=='B'){ printf(lcd_putc,"."); Kd[c]=k; lcd_gotoxy(4+c,2); } else printf(lcd_putc,"%c",k); Kd[c]=k; lcd_gotoxy(4+c,2); } if(k=='A'){ c++; Kd[c]=-92; lcd_gotoxy(4+c,2); } } if(k=='D'){ int j=0; for(;;){ Kd[j]=0; if(j==5) break; j++; } c=0; lcd_gotoxy(1,2); lcd_putc("Kd: "); lcd_gotoxy(4+c,2); } if(k=='*'){ Kd[c+1]=-92; goto S_p; } } //FUERA WHILE lcd_gotoxy(4+c-1,2); lcd_send_byte(0,0x0f); k=0; for(;;){ k=kbd_getc(); if(k!=0){ if(k=='*'){ break; } } } ///SP S_p: lcd_gotoxy(12,2); lcd_send_byte(0,0x0f); c=0; k=0; while(c<=4){ k=kbd_getc(); if(k!=0){ if(k!='A' && k!='*'){ if(k=='B'){ printf(lcd_putc,"."); Sp[c]=k; lcd_gotoxy(12+c,2); } else printf(lcd_putc,"%c",k); Sp[c]=k; lcd_gotoxy(12+c,2); } if(k=='A'){ c++; Sp[c]=-92; lcd_gotoxy(12+c,2); } } if(k=='D'){ int j=0; for(;;){ Sp[j]=0; if(j==5) break; j++; } c=0; lcd_gotoxy(9,4); lcd_putc("Sp: "); lcd_gotoxy(12+c,2); } if(k=='*'){ Sp[c+1]=-92; goto PID; } } lcd_gotoxy(12+c-1,2); lcd_send_byte(0,0x0f); k=0; for(;;){ k=kbd_getc(); if(k!=0){ if(k=='*'){ break; } } } PID: printf(lcd_putc, "\f"); // Borra la pantalla lcd_gotoxy(4, 1); printf(lcd_putc, "procesando.. "); delay_ms(600); float result; a1 = conv(Kp); b1 = conv(Ki);c1 = conv(Kd);ref = conv(Sp); // strtod(cc,NULL); lcd_init(); iT0=0.0; eT0=0.0; min=0.0; //inicialización variables uT = 0.0; max=1023; while(True){ Temp=(float)read_adc(); yT=Temp*5.0/1024.0; rT=ref; eT=rT-yT; //Cálculo error lcd_gotoxy(1,2); printf(lcd_putc,"error:%f",eT); iT=b1*eT+iT0; //Cálculo del término integral dT=c1*(eT-eT0); //Cálculo del término derivativo uT=iT+a1*eT+dT; //Cálculo de la salida PID lcd_gotoxy(1,1); printf(lcd_putc,"Out:%f",uT); if (uT>max) { //Salida PID si es mayor que el MAX uT=max;} else { if (uT<min){ //Salida PID si es menor que el MIN uT=min;} } control=uT; //Transferencia de salida PID a señal PWM lcd_gotoxy(10,1); printf(lcd_putc,"Sp:%f",ref); set_pwm1_duty(control); iT0=iT; //Guardar variables eT0=eT; delay_ms(20); } } }
void main() { //Configuraciones del PIC------------------------------------------------------- //Configuración de puertos... set_tris_A(0x0B); set_tris_B(0xFF); set_tris_C(0x80); set_tris_D(0x00); lcd_init(); dht_init(); //Parámetros del ADC... setup_adc(ADC_CLOCK_INTERNAL); //Reloj interno para conversiones setup_adc_ports(AN0_AN1_AN3); //Puertos usados como entradas //Parámetros para el PWM... setup_ccp1(CCP_PWM); //Módulo PWM activado setup_timer_2(T2_DIV_BY_4,249,1); //Onda de 4KHz //Parámetros de Timer0... setup_timer_0(RTCC_INTERNAL|RTCC_DIV_16); //4ms para desbordamiento //Interrupciones... enable_interrupts(INT_RB); //Interrupción puerto B enable_interrupts(INT_RTCC); //Interrupción Timer0 enable_interrupts(INT_RDA); //Interrupción RS-232 enable_interrupts(GLOBAL); //Análisis de la bandera... set_pwm1_duty(0); lcd_init(); if(read_eeprom(0x00) == 0) { //LM35-------------------------------------------------------------------------- bitRes1=read_eeprom(0x01); cadEnv1=read_eeprom(0x02); offSens1=(float)read_eeprom(0x03)/10.0; if(read_eeprom(0x04)==0) offSens1*=-1.0; //------------------------------------------------------------------------------ //RHT03------------------------------------------------------------------------- cadEnv2=read_eeprom(0x06); offSens2=(float)read_eeprom(0x07)/10.0; if(read_eeprom(0x08)==0) offSens2*=-1.0; //------------------------------------------------------------------------------ //LDR--------------------------------------------------------------------------- bitRes3=read_eeprom(0x0A); cadEnv3=read_eeprom(0x0B); offSens3=(float)read_eeprom(0x0C)/10.0; if(read_eeprom(0x0D)==0) offSens3*=-1.0; //------------------------------------------------------------------------------ //PWM--------------------------------------------------------------------------- pwmSens=read_eeprom(0x0F); threshold[0]=read_eeprom(0x10); threshold[1]=read_eeprom(0x11); threshold[2]=read_eeprom(0x12); threshold[3]=read_eeprom(0x13); //------------------------------------------------------------------------------ } //------------------------------------------------------------------------------ while(true){ //Al presionar aceptar o cancelar se limpia el display.------------------------- if(cls){ cls=false; lcd_init(); } //Lectura de los sensores------------------------------------------------------- if(readSens){ readSens=false; ReadSensData(); } //Muestra las lecturas o configuraciones en el display-------------------------- if(!enterConfig && !displayConfigs) ShowDisplay(); else if(displayConfigs && !enterConfig) ShowConfigs(); if(enterConfig){ if(selector==1) ConfigLM35(); else if(selector==2) ConfigRHT03(); else if(selector==3) ConfigLDR(); else if(selector==4) ConfigPWM(); } if(save==true){ save=false; SaveC(); } //Control del ventilador-------------------------------------------------------- FanRPM(); //Lectura del búfer------------------------------------------------------------- if(read){ ReadBuffer(); ExecCmd(); SaveC(); } //Envío a la PC----------------------------------------------------------------- if(sendData){ sendData=false; if(segs1==cadEnv1){ MakeNSendFrame(1); segs1=0; } if(segs2==cadEnv2){ MakeNSendFrame(2); segs2=0; } if(segs3==cadEnv3){ MakeNSendFrame(3); segs3=0; } }//End if sendData }//End while }