Пример #1
0
void main()
{
	//initialisation du PIC
	setup_adc_ports(NO_ANALOGS);        //on gère toutes les entrées comme étant de type numérique

	enable_interrupts(INT_TIMER2);      //configuration des interruptions
	enable_interrupts(GLOBAL);

	setup_timer_2(T2_DIV_BY_4,250,5);   //setup up timer2 to interrupt every 1ms
	can_init();							//initialise le CAN
	restart_wdt();

	#ifdef DEBUG
	   // Mise en évidence d'un problème lié au Watchdog
   	   switch ( restart_cause() )
       {
          case WDT_TIMEOUT:
          {
             printf("\r\nRestarted processor because of watchdog timeout!\r\n");
             break;
          }
          case NORMAL_POWER_UP:
          {
             printf("\r\nNormal power up! PIC initialized \r\n");
             break;
          }
       }
       restart_wdt();
    #endif



	//  BOUCLE DE TRAVAIL
	while(TRUE)
	{
		restart_wdt();
		listenCAN();
	}
}
adc_init()
{
  /*enable_interrupts(global);
  enable_interrupts(int_rda);
  setup_adc_ports(ALL_ANALOG);
  setup_adc(ADC_CLOCK_INTERNAL); 
  */
  setup_adc_ports(AN0_TO_AN4|VSS_VREF); 
  setup_adc(ADC_CLOCK_INTERNAL); 
  enable_interrupts(global);
  /* 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_DIV_BY_1,60,5); 
  setup_timer_3(T3_DISABLED|T3_DIV_BY_1); 
  setup_comparator(NC_NC_NC_NC); 
 */

}
Пример #3
0
//------------------------------------------------------------------------------
void main(){
   int i;
   
   setup_adc_ports(NO_ANALOGS|VSS_VDD);
   setup_adc(ADC_CLOCK_DIV_2|ADC_TAD_MUL_0);
   setup_psp(PSP_DISABLED);
   setup_spi(SPI_SS_DISABLED);
   setup_wdt(WDT_OFF);
   setup_timer_0(RTCC_INTERNAL|RTCC_DIV_32);
   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);
   setup_vref(FALSE);
   disable_interrupts(INT_TIMER0);
   enable_interrupts(INT_RDA);
   enable_interrupts(GLOBAL);
   setup_oscillator(OSC_8MHZ|OSC_TIMER1|OSC_31250|OSC_PLL_OFF);

   output_low(PIN_C5);
	
   while(TRUE){

      if(f_process){
         f_process=0;
         output_toggle(PIN_C5);
         disable_interrupts(INT_RDA);
			printf("\n\r");
         for(i=0;i<(cont-2);i++){
         	printf("vector[%u]=%c\n\r",i,p[i]); //muestro los datos recibidos
         }
         procesar_guardar();
         cont=0;
         printf("Fin programacion\n\r");
         enable_interrupts(INT_RDA);
      }
   }
}
Пример #4
0
//------------------------------------------------------------------------------
void init_prog(void)
{
setup_wdt(WDT_OFF);
setup_adc_ports(NO_ANALOGS|VSS_VDD);
setup_adc(ADC_OFF);
setup_psp(PSP_DISABLED);                                                
setup_spi(SPI_SS_DISABLED);
setup_timer_0(RTCC_INTERNAL|RTCC_DIV_16|RTCC_8_BIT);// TIMER0
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);                                           
setup_vref(FALSE);
setup_low_volt_detect(FALSE);              
setup_oscillator(OSC_32MHZ);                                        

set_tris_a(0x00);
set_tris_b(0x24); 
set_tris_c(0x80);
set_tris_d(0x00);                                      
set_tris_e(0x15);     
set_tris_f(0x58);
set_tris_g(0x10);
output_a(0x00);
output_b(0x00);
output_c(0x00);
output_d(0x00);
output_e(0x00);
output_f(0x00);
output_g(0x00);
// RF Modul and PA/LNA activation
 
   IOpin.modulepower=0;
   IOpin.moduleCTX=1;
   IOpin.moduleCPS=0;
   IOpin.modulePWRUP=1;
   
}
Пример #5
0
void main()
{
    int8    val;
    char car;

    // Initialization
    delay_ms(400);
    disable_interrupts(global);
    disable_interrupts(int_timer1);
    disable_interrupts(int_timer2);
    disable_interrupts(int_ext);
    setup_adc_ports(NO_ANALOGS|VSS_VDD);
    setup_adc(ADC_OFF|ADC_TAD_MUL_0);
    setup_spi(FALSE);
    setup_wdt(WDT_OFF);
    setup_timer_0(RTCC_INTERNAL);
    setup_timer_1(T1_INTERNAL|T1_DIV_BY_1);
    setup_timer_2(T2_DIV_BY_1,2,1);
    setup_timer_3(T3_DISABLED|T3_DIV_BY_1);
    setup_comparator(NC_NC_NC_NC);
    setup_vref(FALSE);
    setup_low_volt_detect(FALSE);
    setup_oscillator(False);
    delay_ms(400);
    
    while(1)
    {
        val = input(PIN_B0);
        if (val == 0)
        {
            output_a(0);
        }
        else if (val == 1)
        {
            output_a(255);
        }
    }
}
Пример #6
0
// ************************************************
// Funcion Principal
void main()
{
   setup_adc_ports(AN0_AN1_AN3);
   setup_adc(adc_clock_div_32);
   lcd_init();

      while(TRUE)
         {
            m=teclado();
            if(m!=0)
            {
            lcd_putc("\f");
            if(m==49){
            lect_adc(0);}
            else if(m==50){
            lect_adc(1);}
            else {
            printf(lcd_putc,"Tecla invalida");
            }
            delay_ms(50);
            }
          }  
}
Пример #7
0
void main (){
   float Radc;
   int Vadc;   // Voltaje ADC
   char q;
   Ini_USART();
   setup_adc_ports(AN0);
   setup_adc(adc_clock_div_32);
   lcd_init();
   
   while (TRUE){  
      set_adc_channel(0);
      delay_us(20);
      Radc=read_adc();
      delay_us(20);
      Radc = Radc*5.0/1024;
      Vadc = Radc;
      q = Vadc+48;
      USART_SendC(q);
      printf(lcd_putc,"\fV: %f", Radc);
      delay_ms(500);
   }

}
Пример #8
0
void main()
{
   setup_adc_ports(NO_ANALOGS);        //TODO : vérifier s'il existe des entrées analogiques pour le TdB
   set_tris_a(0b00110001);
   set_tris_c(0b00010100);
   set_tris_d(0b01110001);
   set_tris_e(0b00000001);

   enable_interrupts(INT_TIMER2);
   enable_interrupts(INT_TIMER1);
   enable_interrupts(GLOBAL);

   setup_timer_2(T2_DIV_BY_4,79,16);    //Le Timer 2 reprend à zéro toutes les millisecondes environ.

   can_init();
   can_set_baud();

   //  BOUCLE DE TRAVAIL
   while(TRUE)
   {
      internalLogic();
      manageCAN();
   }
}
Пример #9
0
void main()
{

   char dato=0;
   int16 lectura=0;

   setup_adc_ports(AN0);
   setup_adc(ADC_CLOCK_INTERNAL);
//CONFIGURACIÓN BUS SPI-------------------------------------------------------------
 setup_spi(spi_master | spi_l_to_h | spi_clk_div_16);//Vamos a trabajar como maestro|que funciona en activo alto
 //lcd_init();
 set_adc_channel(0);
 
 while(true)
 {
  set_adc_channel(0);
  delay_ms(200);
  lectura=read_adc();
  spi_write(lectura);//Escribir lo que haya en el pin A0
  //lcd_gotoxy(1,1);
  //printf(lcd_putc," %Ld   ",lectura);
 // delay_ms(200);
 }
}
Пример #10
0
void main()
{

   setup_adc_ports(NO_ANALOGS);
   setup_adc(ADC_OFF);
   setup_spi(SPI_SS_DISABLED);
   setup_timer_0(RTCC_INTERNAL|RTCC_DIV_1);
   setup_timer_1(T1_DISABLED);
   setup_timer_2(T2_DISABLED,0,1);
   setup_comparator(NC_NC_NC_NC);
   setup_vref(FALSE);
   
   PORT_C.6 = 0;
   PORT_C.7 = 1;
   
   set_tris_c(X);
   
   while(1)
   {
      printf("RS 232");
      getc();
      putc(getc());
   }
}
Пример #11
0
void main()
{
   disable_interrupts(GLOBAL);
   
   setup_spi(SPI_MASTER | SPI_MODE_0_0 | SPI_CLK_DIV_16 );
   setup_spi2(SPI_MASTER | SPI_MODE_0_0 | SPI_CLK_DIV_16 );
   
   setup_adc_ports(sAN0|sAN1|sAN2|sAN3|sAN4|VSS_4V096);
   setup_adc(ADC_CLOCK_INTERNAL|ADC_TAD_MUL_0);

   // TIMER 0 is being used to service the WTD
   setup_timer_0(T0_INTERNAL|T0_DIV_256);
   /* sets the internal clock as source and prescale 256. 
      At 10 Mhz timer0 will increment every 0.4us (Fosc*4) in this setup and overflows every
      6.71 seconds. Timer0 defaults to 16-bit if RTCC_8_BIT is not used.
      Fosc = 10 MHz, Fosc/4 = 2.5 Mhz, div 256 = 0.0001024 s, 65536 increments = 6.71 sec
      Fosc = 64 MHz, Fosc/4 = 16 Mhz, div 256 = 0.000016 s, 65536 increments = 1.05 sec
      .. pre-load with 3036 to get exact 1.0000 sec value
   */
   
   // TIMER 1 is used to extinguish the LED
   setup_timer_1(T1_INTERNAL|T1_DIV_BY_8);
   /* sets the internal clock as source and prescale 4. 
      At 10Mhz timer0 will increment every 0.4us in this setup and overflows every
      104.8 ms. Timer1 is 16-bit.
      Fosc = 10 Mhz ... 2.5 MHz / div 4  = 0.00000160 s * 65536 = 0.104858 sec
      Fosc = 64 Mhz ... 16 MHz /  div 4  = 0.00000025 s * 65536 = 0.016384 sec
      Fosc = 64 Mhz ... 16 MHz /  div 8  = 0.00000200 s * 65536 = 0.032768 sec
   */   
   
   setup_stepper_pwm();  // Uses TIMER 2
   
   // TIMER 3 is used for stepper motor intervals
   setup_timer_3(T3_INTERNAL | T3_DIV_BY_1);   // 16 bit timer
   
   // TIMER 4 is use for serial time-outs. 8-bit timer.
   setup_timer_4(T4_DIV_BY_4, 127, 1);           
   
   setup_comparator(NC_NC_NC_NC);
   
   setup_oscillator(OSC_16MHZ | OSC_PLL_ON);  // Fosc = 64 MHz
          
   ext_int_edge(0, H_TO_L);         // Set up PIC18 EXT0
   enable_interrupts(INT_EXT);
   
   start_heartbeat();
   
   enable_interrupts(GLOBAL);

   init_hardware();
   motor_sleep_rdy();
   
   sleep_mode = FALSE;   
   busy_set();
   
   init_nv_vars();
   get_step_vars();
   init_aws();
   
   blink();
   
   //Add for TCP/IP interface
   //delay_ms(15000);
   
   signon();
   
   RTC_read();
   RTC_last_power();
   RTC_reset_HT();  
   RTC_read();    
   RTC_read_flags();
   
   if(nv_sd_status>0) fprintf(COM_A,"@SD=%Lu\r\n", nv_sd_status);
   init_rtc(); // This is the FAT RTC
   sd_status = init_sdcard();
   if(sd_status>0) msg_card_fail();
   
   reset_event();
   
   if(m_error[0] > 0 || m_error[1] > 0) msg_mer();  
   
   if (m_comp[0]==FALSE) {
      e_port[0]=0;
      write16(ADDR_E1_PORT,0);
      fprintf(COM_A, "@MC1,%Lu,%Ld\r\n", m_comp[0],e_port[0]);
   }
   if (m_comp[1]==FALSE) {
      m_lin_pos[1]=-1;
      write16(ADDR_M2_LIN_POS, -1);
      fprintf(COM_A, "@MC2,%Lu,%Ld\r\n", m_comp[1],m_lin_pos[1]);
   }
   
   if (nv_cmd_mode == FALSE){
      for(dt=0; dt<100; ++dt){
         blip();
         if (nv_cmd_mode == TRUE) {
            busy_clear();
            fputs("@OK!", COM_A);
            command_prompt();
            dt = 100;
         }
      }
   }
   else command_prompt();
   
   user_quit = auto_sample_ready();
   
   reset_cpu();
}
Пример #12
0
void main()
{

   setup_adc_ports(NO_ANALOGS);
   setup_adc(ADC_OFF);
   setup_spi(SPI_SS_DISABLED);
   setup_timer_0(RTCC_INTERNAL|RTCC_DIV_32);
   setup_timer_1(T1_DISABLED);
   setup_timer_2(T2_DISABLED,0,1);
   setup_comparator(NC_NC_NC_NC);
   setup_vref(FALSE);
   enable_interrupts(INT_RDA);
   enable_interrupts(INT_TIMER0);
   enable_interrupts(GLOBAL);
   //port_b_pullups(TRUE);
   set_timer0(131);
   // TODO: USER CODE!!

andares[0] = 0;
andares[1] = 0;
andares[2] = 0;
andares[3] = 0;
sinal = 0;

   set_tris_a(0x00); //saída de dados
   set_tris_b(0xfe); //entrada de dados,menos bit 0
   set_tris_c(0xbf); //saída de dados, menos bit 6
   
   while(TRUE){
    conta = 0;
    
         if(andares[0] != 0){
            if(andares[0] == 1) TMP1 = 0; 
            if(andares[0] == 2) TMP1 = 100;
            if(andares[0] == 3) TMP1 = 200;
            if(andares[0] == 4) TMP1 = 300;
            
          if(TMP2 < TMP1) motor_passo_frente(TMP1-TMP2);
          else motor_passo_tras(TMP2-TMP1);
     
          conta = 0;
          sinal = 1;
          parar_motor_passo();
          printf("Você está no andar %d",andares[0]);
          tira_andar(andares);
          while(conta != 125);
          sinal = 0;

         }else{
          parar_motor_passo();
          sinal = 1;
        }

    TMP2 = TMP1;
     
    if(!parada){
    while(!parada){
    delay_ms(30);
    parou = 1;
    }
    }

       if(parou){
           printf("Opa!parada de emergência");
           sinal = 0; 
           
       TMP2 = TMP1;
   
            do{
            parar_motor_passo();
            
            if(!parada){
            while(!parada){
            delay_ms(30);
            parou = 0;
            }
            }while(!parou);
            printf("Prosseguindo...");
            sinal = 1;
        }    

        if(!andar1 || !andar2 || !andar3 || !andar4){
          while(!andar1 || !andar2 || !andar3 || !andar4){
            delay_ms(30);
            if(!andar1) botao = 1; 
            if(!andar2) botao = 2;
            if(!andar3) botao = 3;
            if(!andar4) botao = 4;
            insere_andar(andares,i);
            ordena(andares);
          }
        }

debug();
         
               
   }

}

}
Пример #13
0
void main()
{

   setup_adc_ports(NO_ANALOGS|VSS_VDD);
   setup_adc(ADC_CLOCK_DIV_2);
   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_timer_3(T3_DISABLED|T3_DIV_BY_1);
   setup_comparator(NC_NC_NC_NC);
   setup_vref(FALSE);
   enable_interrupts(INT_TIMER0);
   enable_interrupts(GLOBAL);
//Setup_Oscillator parameter not selected from Intr Oscillator Config tab

   set_tris_a(0b00000011);
   set_tris_b(0b00000000);
   set_tris_c(0b10110011);
   set_tris_d(0b11110000);
   set_tris_e(0b00000100);
   
   while(1)
   {
  
      // waits for B1 to go high
      while ( !input(PIN_B1) )
      {}




   
      //PE-
      playSound(NOTE_SOL3,TEMPS_NOIRE);
      delay_us(WAIT);
      //--------------------------------
      //tit
      playSound(NOTE_DO4,TEMPS_NOIRE);
      delay_us(WAIT);
      //pa-
      playSound(NOTE_DO4,TEMPS_NOIRE);
      delay_us(WAIT);
      //pa
      playSound(NOTE_DO4,TEMPS_NOIRE);
      delay_us(WAIT);
      //Noe-
      playSound(NOTE_RE4,TEMPS_NOIRE);
      delay_us(WAIT);
      //--------------------------------
      //el
      playSound(NOTE_DO4,TEMPS_BLANCHE);
      playSound(NOTE_DO4,TEMPS_NOIRE);
      delay_us(WAIT);
      //Quand
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //tu
      playSound(NOTE_RE4,TEMPS_CROCHE);
      delay_us(WAIT);
      //--------------------------------
      //Des-
      playSound(NOTE_MI4,TEMPS_NOIRE);
      delay_us(WAIT);
      //cen-
      playSound(NOTE_MI4,TEMPS_NOIRE);
      delay_us(WAIT);
      //dras
      playSound(NOTE_MI4,TEMPS_NOIRE);
      delay_us(WAIT);
      //du
      playSound(NOTE_FA4,TEMPS_NOIRE);
      delay_us(WAIT);
      //--------------------------------
      //ciel
      playSound(NOTE_MI4,TEMPS_BLANCHE);
      playSound(NOTE_MI4,TEMPS_NOIRE);
      delay_us(WAIT);
      //A-
      playSound(NOTE_RE4,TEMPS_NOIRE);
      delay_us(WAIT);
      //--------------------------------
      //vec
      playSound(NOTE_DO4,TEMPS_NOIRE);
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //tes
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //jou-
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //ets
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //par
      playSound(NOTE_SI3,TEMPS_CROCHE);
      delay_us(WAIT);
      //mi-
      playSound(NOTE_LA3,TEMPS_CROCHE);
      delay_us(WAIT);
      //--------------------------------
      //liers
      playSound(NOTE_SOL3,TEMPS_BLANCHE);
      playSound(NOTE_SOL3,TEMPS_NOIRE);
      delay_us(WAIT);
      //N'ou-
      playSound(NOTE_SOL3,TEMPS_CROCHE);
      delay_us(WAIT);
      //blie
      playSound(NOTE_SOL3,TEMPS_CROCHE);
      delay_us(WAIT);
      //--------------------------------
      //pas
      playSound(NOTE_DO4,TEMPS_BLANCHE);
      delay_us(WAIT);
      //mon
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //pet-
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //tit
      playSound(NOTE_SI3,TEMPS_CROCHE);
      delay_us(WAIT);
      //pa-
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //--------------------------------
      //nier
      playSound(NOTE_RE4,TEMPS_BLANCHE);
      playSound(NOTE_RE4,TEMPS_NOIRE);
      delay_us(WAIT);
      //Mais
      playSound(NOTE_SOL3,TEMPS_NOIRE);
      delay_us(WAIT);
      //--------------------------------
      //a-
      playSound(NOTE_DO4,TEMPS_NOIRE);
      delay_us(WAIT);
      //vant
      playSound(NOTE_DO4,TEMPS_NOIRE);
      delay_us(WAIT);
      //de
      playSound(NOTE_DO4,TEMPS_NOIRE);
      delay_us(WAIT);
      //par-
      playSound(NOTE_RE4,TEMPS_NOIRE);
      delay_us(WAIT);
      //--------------------------------
      //tir
      playSound(NOTE_DO4,TEMPS_BLANCHE);
      playSound(NOTE_DO4,TEMPS_NOIRE);
      delay_us(WAIT);
      //il
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //fau-
      playSound(NOTE_RE4,TEMPS_CROCHE);
      delay_us(WAIT);
      //--------------------------------
      //dra
      playSound(NOTE_MI4,TEMPS_NOIRE);
      delay_us(WAIT);
      //bien
      playSound(NOTE_MI4,TEMPS_NOIRE);
      delay_us(WAIT);
      //te
      playSound(NOTE_MI4,TEMPS_NOIRE);
      delay_us(WAIT);
      //cou-
      playSound(NOTE_FA4,TEMPS_NOIRE);
      delay_us(WAIT);
      //--------------------------------
      //vrir
      playSound(NOTE_MI4,TEMPS_BLANCHE);
      playSound(NOTE_MI4,TEMPS_NOIRE);
      delay_us(WAIT);
      //De-
      playSound(NOTE_RE4,TEMPS_NOIRE);
      delay_us(WAIT);
      //--------------------------------
      //hors
      playSound(NOTE_DO4,TEMPS_NOIRE);
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //il
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //fait
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //dé-
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //jà
      playSound(NOTE_SI3,TEMPS_CROCHE);
      delay_us(WAIT);
      //bien
      playSound(NOTE_LA3,TEMPS_CROCHE);
      delay_us(WAIT);
      //--------------------------------
      //froid
      playSound(NOTE_SOL3,TEMPS_BLANCHE);
      playSound(NOTE_SOL3,TEMPS_NOIRE);
      delay_us(WAIT);
      //C'est
      playSound(NOTE_SOL3,TEMPS_CROCHE);
      delay_us(WAIT);
      //un
      playSound(NOTE_SOL3,TEMPS_CROCHE);
      delay_us(WAIT);
      //--------------------------------
      //peu
      playSound(NOTE_DO4,TEMPS_BLANCHE);
      delay_us(WAIT);
      //a
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //cau-
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //se
      playSound(NOTE_RE4,TEMPS_CROCHE);
      delay_us(WAIT);
      //de
      playSound(NOTE_RE4,TEMPS_CROCHE);
      delay_us(WAIT);
      //--------------------------------
      //Moi
      playSound(NOTE_DO4,TEMPS_RONDE);
      delay_us(WAIT);
      //--------------------------------
      //Il
      playSound(NOTE_LA3,TEMPS_CROCHE);
      delay_us(WAIT);
      //me
      playSound(NOTE_LA3,TEMPS_CROCHE);
      delay_us(WAIT);
      //tar-
      playSound(NOTE_LA3,TEMPS_CROCHE);
      delay_us(WAIT);
      //de
      playSound(NOTE_LA3,TEMPS_CROCHE);
      delay_us(WAIT);
      //tant
      playSound(NOTE_LA3,TEMPS_NOIRE);
      delay_us(WAIT);
      //que
      playSound(NOTE_LA3,TEMPS_CROCHE);
      delay_us(WAIT);
      //le
      playSound(NOTE_SI3,TEMPS_CROCHE);
      delay_us(WAIT);
      //--------------------------------
      //jour
      playSound(NOTE_DO4,TEMPS_NOIRE);
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //se
      playSound(NOTE_LA3,TEMPS_CROCHE);
      delay_us(WAIT);
      //lè-
      playSound(NOTE_LA3,TEMPS_NOIRE);
      delay_us(WAIT);
      //ve
      playSound(NOTE_SOL3,TEMPS_NOIRE);
      delay_us(WAIT);
      //--------------------------------
      //Pour
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //voir
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //si
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //tu
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //m'as
      playSound(NOTE_DO4,TEMPS_NOIRE);
      delay_us(WAIT);
      //ap-
      playSound(NOTE_SI3,TEMPS_CROCHE);
      delay_us(WAIT);
      //por-
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //--------------------------------
      //té
      playSound(NOTE_RE4,TEMPS_RONDE);
      delay_us(WAIT);
      //--------------------------------
      //tous
      playSound(NOTE_MI4,TEMPS_CROCHE);
      delay_us(WAIT);
      //les
      playSound(NOTE_MI4,TEMPS_CROCHE);
      delay_us(WAIT);
      //beaux
      playSound(NOTE_MI4,TEMPS_CROCHE);
      delay_us(WAIT);
      //jou-
      playSound(NOTE_MI4,TEMPS_CROCHE);
      delay_us(WAIT);
      //joux
      playSound(NOTE_MI4,TEMPS_NOIRE);
      delay_us(WAIT);
      //que
      playSound(NOTE_RE4,TEMPS_CROCHE);
      delay_us(WAIT);
      //je
      playSound(NOTE_MI4,TEMPS_CROCHE);
      delay_us(WAIT);
      //--------------------------------
      //vois
      playSound(NOTE_FA4,TEMPS_NOIRE);
      playSound(NOTE_FA4,TEMPS_CROCHE);
      delay_us(WAIT);
      //en
      playSound(NOTE_RE4,TEMPS_CROCHE);
      delay_us(WAIT);
      //re-
      playSound(NOTE_DO4,TEMPS_NOIRE);
      delay_us(WAIT);
      //ve
      playSound(NOTE_SI3,TEMPS_NOIRE);
      delay_us(WAIT);
      //--------------------------------
      //et
      playSound(NOTE_MI4,TEMPS_CROCHE);
      delay_us(WAIT);
      playSound(NOTE_MI4,TEMPS_CROCHE);
      delay_us(WAIT);
      //que
      playSound(NOTE_MI4,TEMPS_CROCHE);
      delay_us(WAIT);
      //je
      playSound(NOTE_MI4,TEMPS_CROCHE);
      delay_us(WAIT);
      //t'ai
      playSound(NOTE_FA4,TEMPS_NOIRE);
      delay_us(WAIT);
      //com-
      playSound(NOTE_FA4,TEMPS_CROCHE);
      delay_us(WAIT);
      //man-
      playSound(NOTE_FA4,TEMPS_CROCHE);
      delay_us(WAIT);
      //--------------------------------
      //de
      playSound(NOTE_SOL4,TEMPS_BLANCHE);
      playSound(NOTE_SOL4,TEMPS_BLANCHE);
      delay_us(WAIT);
       //PE-
      playSound(NOTE_SOL3,TEMPS_NOIRE);
      delay_us(WAIT);
      //--------------------------------
      //tit
      playSound(NOTE_DO4,TEMPS_NOIRE);
      delay_us(WAIT);
      //pa-
      playSound(NOTE_DO4,TEMPS_NOIRE);
      delay_us(WAIT);
      //pa
      playSound(NOTE_DO4,TEMPS_NOIRE);
      delay_us(WAIT);
      //Noe-
      playSound(NOTE_RE4,TEMPS_NOIRE);
      delay_us(WAIT);
      //--------------------------------
      //el
      playSound(NOTE_DO4,TEMPS_BLANCHE);
      playSound(NOTE_DO4,TEMPS_NOIRE);
      delay_us(WAIT);
      //Quand
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //tu
      playSound(NOTE_RE4,TEMPS_CROCHE);
      delay_us(WAIT);
      //--------------------------------
      //Des-
      playSound(NOTE_MI4,TEMPS_NOIRE);
      delay_us(WAIT);
      //cen-
      playSound(NOTE_MI4,TEMPS_NOIRE);
      delay_us(WAIT);
      //dras
      playSound(NOTE_MI4,TEMPS_NOIRE);
      delay_us(WAIT);
      //du
      playSound(NOTE_FA4,TEMPS_NOIRE);
      delay_us(WAIT);
      //--------------------------------
      //ciel
      playSound(NOTE_MI4,TEMPS_BLANCHE);
      playSound(NOTE_MI4,TEMPS_NOIRE);
      delay_us(WAIT);
      //A-
      playSound(NOTE_RE4,TEMPS_NOIRE);
      delay_us(WAIT);
      //--------------------------------
      //vec
      playSound(NOTE_DO4,TEMPS_NOIRE);
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //tes
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //jou-
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //ets
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //par
      playSound(NOTE_SI3,TEMPS_CROCHE);
      delay_us(WAIT);
      //mi-
      playSound(NOTE_LA3,TEMPS_CROCHE);
      delay_us(WAIT);
      //--------------------------------
      //liers
      playSound(NOTE_SOL3,TEMPS_BLANCHE);
      playSound(NOTE_SOL3,TEMPS_NOIRE);
      delay_us(WAIT);
      //N'ou-
      playSound(NOTE_SOL3,TEMPS_CROCHE);
      delay_us(WAIT);
      //blie
      playSound(NOTE_SOL3,TEMPS_CROCHE);
      delay_us(WAIT);
      //--------------------------------
      //pas
      playSound(NOTE_DO4,TEMPS_BLANCHE);
      delay_us(WAIT);
      //mon
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //pet-
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //tit
      playSound(NOTE_SI3,TEMPS_CROCHE);
      delay_us(WAIT);
      //pa-
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //--------------------------------
      //nier
      playSound(NOTE_RE4,TEMPS_BLANCHE);
      playSound(NOTE_RE4,TEMPS_NOIRE);
      delay_us(WAIT);
      //Mais
      playSound(NOTE_SOL3,TEMPS_NOIRE);
      delay_us(WAIT);
      //--------------------------------
      //a-
      playSound(NOTE_DO4,TEMPS_NOIRE);
      delay_us(WAIT);
      //vant
      playSound(NOTE_DO4,TEMPS_NOIRE);
      delay_us(WAIT);
      //de
      playSound(NOTE_DO4,TEMPS_NOIRE);
      delay_us(WAIT);
      //par-
      playSound(NOTE_RE4,TEMPS_NOIRE);
      delay_us(WAIT);
      //--------------------------------
      //tir
      playSound(NOTE_DO4,TEMPS_BLANCHE);
      playSound(NOTE_DO4,TEMPS_NOIRE);
      delay_us(WAIT);
      //il
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //fau-
      playSound(NOTE_RE4,TEMPS_CROCHE);
      delay_us(WAIT);
      //--------------------------------
      //dra
      playSound(NOTE_MI4,TEMPS_NOIRE);
      delay_us(WAIT);
      //bien
      playSound(NOTE_MI4,TEMPS_NOIRE);
      delay_us(WAIT);
      //te
      playSound(NOTE_MI4,TEMPS_NOIRE);
      delay_us(WAIT);
      //cou-
      playSound(NOTE_FA4,TEMPS_NOIRE);
      delay_us(WAIT);
      //--------------------------------
      //vrir
      playSound(NOTE_MI4,TEMPS_BLANCHE);
      playSound(NOTE_MI4,TEMPS_NOIRE);
      delay_us(WAIT);
      //De-
      playSound(NOTE_RE4,TEMPS_NOIRE);
      delay_us(WAIT);
      //--------------------------------
      //hors
      playSound(NOTE_DO4,TEMPS_NOIRE);
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //il
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //fait
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //dé-
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //jà
      playSound(NOTE_SI3,TEMPS_CROCHE);
      delay_us(WAIT);
      //bien
      playSound(NOTE_LA3,TEMPS_CROCHE);
      delay_us(WAIT);
      //--------------------------------
      //froid
      playSound(NOTE_SOL3,TEMPS_BLANCHE);
      playSound(NOTE_SOL3,TEMPS_NOIRE);
      delay_us(WAIT);
      //C'est
      playSound(NOTE_SOL3,TEMPS_CROCHE);
      delay_us(WAIT);
      //un
      playSound(NOTE_SOL3,TEMPS_CROCHE);
      delay_us(WAIT);
      //--------------------------------
      //peu
      playSound(NOTE_DO4,TEMPS_BLANCHE);
      delay_us(WAIT);
      //a
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //cau-
      playSound(NOTE_DO4,TEMPS_CROCHE);
      delay_us(WAIT);
      //se
      playSound(NOTE_RE4,TEMPS_CROCHE);
      delay_us(WAIT);
      //de
      playSound(NOTE_RE4,TEMPS_CROCHE);
      delay_us(WAIT);
      //--------------------------------
      //Moi
      playSound(NOTE_DO4,TEMPS_BLANCHE);
      playSound(NOTE_DO4,TEMPS_NOIRE);
      delay_us(WAIT);
      
      playSound(NOTE_SOL3,TEMPS_NOIRE);
      delay_us(WAIT);
      //--------------------------------
      playSound(NOTE_LA3,TEMPS_NOIRE);
      delay_us(WAIT);
      playSound(NOTE_DO4,TEMPS_NOIRE);
      delay_us(WAIT);
      playSound(NOTE_RE4,TEMPS_NOIRE);
      delay_us(WAIT);
      playSound(NOTE_FA4,TEMPS_NOIRE);
      delay_us(WAIT);
      //--------------------------------
      playSound(NOTE_SOL4,TEMPS_RONDE);
      delay_us(WAIT);
   }
   
   
   
}
Пример #14
0
void main()
{
   port_b_pullups(TRUE);      // Pullupy pro pripojeni tlacitka

   
   setup_adc_ports(NO_ANALOGS);
   setup_adc(ADC_OFF);
   setup_spi(SPI_SS_DISABLED);
   setup_timer_0(RTCC_EXT_L_TO_H|RTCC_DIV_1);
   setup_timer_1(T1_EXTERNAL|T1_DIV_BY_8|T1_CLK_OUT);
   setup_timer_2(T2_DISABLED,0,1);
   setup_comparator(NC_NC_NC_NC);
   setup_vref(FALSE);
   
   
   enable_interrupts(INT_TIMER1);
   enable_interrupts(INT_TIMER0);
   enable_interrupts(GLOBAL);

ODROID_ON_1; //zapnutí napájení odroidu
delay_ms(10);
ODROID_ON_0;
ODROID_I=1;

PCDR_ON_1; //zapnutí napájení PCDR
delay_ms(10);
PCDR_ON_0;
PCDR_I=1;

GPS_ON_1; //zapnutí napájení GPS
delay_ms(10);
GPS_ON_0;
GPS_I=1;

GPRS_ON_1; //zapnutí napájení GPRS
delay_ms(10);
GPRS_ON_0;
GPRS_I=1;
      
   while(TRUE)
   {

//----------------------------------------------------------------------
//----------------------------------------------------------------------
   //osetruje odpojeni napajeni ODROIDU na externí pokyn
   if(IN_ODROID)
      {
      if(ODROID_I)
         {
         ODROID_OFF_1;           // odpojí relé
         delay_ms(10);
         ODROID_OFF_0;
         ODROID_I=0;
         }
         else
         {
         }
       }     
      else
      {
     
       
      if(ODROID_I)
         {
         }
         else
         {
         ODROID_ON_1;           // pripojí relé
         delay_ms(10);
         ODROID_ON_0;
         ODROID_I=1;
         }
     
      }
      
      
//----------------------------------------------------------------------
//----------------------------------------------------------------------
   //osetruje odpojeni napajeni PCDR na externí pokyn
   if(IN_PCDR)
      {
      if(PCDR_I)
         {
         PCDR_OFF_1;           // odpojí relé
         delay_ms(10);
         PCDR_OFF_0;
         PCDR_I=0;
         }
         else
         {
         }
       }     
      else
      {
     
       
      if(PCDR_I)
         {
         }
         else
         {
         PCDR_ON_1;           // pripojí relé
         delay_ms(10);
         PCDR_ON_0;
         PCDR_I=1;
         }
      
     
      }
      
      
//----------------------------------------------------------------------
//----------------------------------------------------------------------
   //osetruje odpojeni napajeni GPS na externí pokyn
   if(IN_GPS)
      {
      if(GPS_I)
         {
         GPS_OFF_1;           // odpojí relé
         delay_ms(10);
         GPS_OFF_0;
         GPS_I=0;
         }
         else
         {
         }
       }     
      else
      {
     
       
      if(GPS_I)
         {
         }
         else
         {
         GPS_ON_1;           // pripojí relé
         delay_ms(10);
         GPS_ON_0;
         GPS_I=1;
         }      
      }
      
 //----------------------------------------------------------------------
//----------------------------------------------------------------------
   //osetruje odpojeni napajeni GPRS na externí pokyn
   if(IN_GPRS)
      {
      if(GPRS_I)
         {
         GPRS_OFF_1;           // odpojí relé
         delay_ms(10);
         GPRS_OFF_0;
         GPRS_I=0;
         }
         else
         {
         }
       }     
      else
      {
     
       
      if(GPRS_I)
         {
         }
         else
         {
         GPRS_ON_1;           // pripojí relé
         delay_ms(10);
         GPRS_ON_0;
         GPRS_I=1;
         }           
      }
      
      
      
      
      
     } 
     

} 
Пример #15
0
void main(){

setup_timer_0(RTCC_INTERNAL|RTCC_DIV_256);
setup_timer_1(T1_DISABLED);
setup_oscillator (OSC_8MHZ);
setup_adc_ports(NO_ANALOGS|VSS_VDD);
setup_adc(ADC_OFF);
setup_comparator(NC_NC_NC_NC);
setup_vref(FALSE);

//Software workaround for the power switch floating
/*
onewire_init();
onewire_sendbyte(0xCC);
onewire_sendbyte(0x6C);    //Write Data Command
onewire_sendbyte(0x31);    //Eeprom address but actually gets written to Shadow Ram
onewire_sendbyte(0xE7);    //Value to make PMOD1 SWEN=0 RNAOP=0

//Copy the shadow Ram written above over to actual EEPROM
onewire_init();
onewire_sendbyte(0xCC);
onewire_sendbyte(0x48);    //send the copy command
onewire_sendbyte(0x30);    //copy shadow ram to the block containing 31
*/
for (i=1;i<5;i++){
output_high(pin_A4);
delay_ms(250);
output_low(pin_A4);
delay_ms(250);
}

while(true){

//Use the following to determine the state of the one wire net
//Will report if device present, not, or shorted
//Comment out rest of code
//onewire_init_with_error_check();
//read_status();
//printf("status byte is ====>(%x)\n\r",status);
//printf("Please enter a command (h for help):\n\r");

//Waits for a command to come in over the serial port   
//printf("Enter Command\n\r");
//Base commands are:
//N =  Print out the net address of one attached sensor
//K =  Return the current in micro volts
//C =  Return the chip temperature in celsius
//F =  Return the chip temperature in fahrenheit
if (interactive == 1)
   printf("Enter Command:\n\r");
gets(command);
//Check to see if controller is present   
if (command[0] == 'p'){
   printf("Pyro Logger found and responding...\n\r");
   printf("Firmware Version 1\n\r");
   printf("N - Get Net address\n\r");
   printf("Kaddress - Thermo uV's\n\r");
   printf("Caddress - Temp in C\n\r");
   printf("Faddress - Temp in F\n\r");
   printf("i - toggle interactive\n\r");
   interactive = 1;
}

if (command[0] == 'i'){
   interactive = 0;
}



//Print out the Net address for configuring other software   
if (command[0] == 'N'){
   printf("Reading Net Address...\r\n");
         read_netaddress();
}
//****************************************************
//READ Current from Sensor
//****************************************************
if (command[0] == 'K'){
   
//Initialize the Temporary Buffer and make sure you have the null char
tmp_buff[0]='0';
tmp_buff[1]='X';
tmp_buff[2]='0';
tmp_buff[3]='0';
tmp_buff[4]='\n';
   
   i=0;
   for(j=1; j<=15; j+=2) {
   tmp_buff[2]=command[j];
   tmp_buff[3]=command[j+1];
   address_array[i]=ATOI(tmp_buff);
   i++;   
}
onewire_init();
onewire_sendbyte(0x55);  //Transmit skip Rom Command
//Unique 64 Bit address
for(j=0; j<=7; j++)
{
onewire_sendbyte(address_array[j]);
}
onewire_sendbyte(0x69);  //0x69 Transmit Read RAM command
onewire_sendbyte(0x0E); //Transmit Read start address
data_MSB=onewire_readbyte();
data_LSB=onewire_readbyte();
//printf("MSB ====>(%x)\n\r",data_MSB);
//printf("LSB ====>(%x)\n\r",data_LSB);
current=make16(data_MSB,data_LSB);
current=current >> 3;
current_float=(current*.000015625);
printf("%4.7f\r\n",current_float);
blink();
}

//***********************************************************
//Read Temperature of the on Chip Sensor
//***********************************************************
//DS2760 can measure 0.125 deg C per bit
//Whole number temperature values can be had by simpling taking the high byte
//Or if high and low bytes are used shift right 5 places and multiply by .125 in a float

if (command[0] == 'C' || command[0] == 'F'){
//Initialize the Temporary Buffer and make sure you have the null char
tmp_buff[0]='0';
tmp_buff[1]='X';
tmp_buff[2]='0';
tmp_buff[3]='0';
tmp_buff[4]='\n';

//Pull the address out of the command 8 bytes of HEX
//Changes it from a string  to array stuffed in address_array   
   i=0;
   for(j=1; j<=15; j+=2) {
   tmp_buff[2]=command[j];
   tmp_buff[3]=command[j+1];
   address_array[i]=ATOI(tmp_buff);
   i++;   
}

//Send the addresss down the One Wire Buss
onewire_init();
onewire_sendbyte(0x55); //Match Net Address Command 
for(j=0;j<=7;j++){
onewire_sendbyte(address_array[j]);
}

//Read Data
onewire_sendbyte(0x69);  //0x69 Transmit Read RAM command
onewire_sendbyte(0x18); //Transmit Read start address
data_MSB=onewire_readbyte();
data_LSB=onewire_readbyte();
temp=make16(data_MSB,data_LSB);

//Check for a negative temperature for cold junction.  Really cold junction 
//can only be positive or zero.  Cold junction reference should never fall below zero
//so if its below zero  make it zero, about the best we could do aside throwing up errors
//To force temperature negative for testing uncomment below
//temp = temp + 32768;

//The Check
if (bit_test(temp,15) == 1)
   temp = 0;

/*
//Bit Shift Math For Whole Number Only
temp=temp>>8;
temp_float = temp;
*/
//Shift the data 5 bits to the right
temp=temp >> 5;

//Math for celsius
temp_float=(temp *.125);
//Math for fahrenheit
temp_float_faren=((temp_float * 1.8) + 32);


//Print out either celsius or fahrenheit
//Over the serial Port
if (command[0] == 'C' )
   printf("%3.2f\r\n",temp_float);
if (command[0] == 'F' )
   printf("%3.2f\r\n",temp_float_faren);
   
//Flash the leds to show there is communication
blink();
}
Пример #16
0
//*****************************************************************************************
//*****************************************************************************************
//P RO G R A M A     P R I N C I P A L
//*****************************************************************************************
//*****************************************************************************************
void main(){
   float32* fltPtr;
   float32 varX,varY,varZ;
   float32 Xp,Yp;
   float32 fx,fy,fz;
   float incX;
   float incY;
   
   char x,y,z;
   char posicion;

   setup_adc_ports(NO_ANALOGS|VSS_VDD);
   setup_adc(ADC_OFF|ADC_TAD_MUL_0);
   setup_psp(PSP_DISABLED);
   setup_spi(SPI_SS_DISABLED);
   setup_spi2(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_timer_3(T3_DISABLED|T3_DIV_BY_1);
   setup_timer_4(T4_DISABLED,0,1);
   setup_comparator(NC_NC_NC_NC);
   setup_vref(FALSE);

   set_tris_a(0x00);
   set_tris_b(0x00);
   set_tris_c(0xC0);
   set_tris_d(0x00);
   set_tris_e(0x00);

   DELAY_MS(200);

   output_b(0xFF);

   GLCD_init(1);

   DELAY_MS(500);

   output_b(0x00);

   //Setear propiedades de la grafica.
   graph.x1=0.0;
   graph.y1=0.0;
   graph.x2=127.0;
   graph.y2=63.0;

   graph.minX=-1.0;
   graph.maxX=1.0;
   graph.minY=-1.0;
   graph.maxY=1.0;

   graph.minViewX=-2.5;
   graph.maxViewX=2.5;
   graph.minViewY=-1.25;
   graph.maxViewY=1.25;

   printf("Hecho por Bruno Fascendini @ 2009 para uControl y Todopic\r\ncomo parte de proyecto calculadora cientifica con PIC del foro uControl\r\n");
   printf("Parseador version: %s Evaluador version: %s\r\n",ParserVer,EvaluadorVer);
   //menú:
   printf("Ingrese la superficie a graficar: ");

   posicion=0;
   do{
      EquIn[posicion]=getc();
      if(posicion>0 && EquIn[posicion]==8) posicion--; else posicion++;      //delete if delete key pressed...
      if(posicion==BUFFER_SIZE) break;
   }while(EquIn[posicion-1]!=13);
   EquIn[posicion]='\0';

   printf("Ha pedido que se grafique la ecuacion: %s",EquIn);

   printf("Ingrese valor minimo de x: ");
   posicion=0;
   do{
      temp[posicion]=getc();
      if(posicion>0 && temp[posicion]==8) posicion--; else posicion++;      //delete if delete key pressed...
      if(posicion==BUFFER_SIZE) break;
   }while(temp[posicion-1]!=13);
   temp[posicion]='\0';
   graph.minX=atof(temp);
   
   printf("Ingrese valor maximo de x: ");
   posicion=0;
   do{
      temp[posicion]=getc();
      if(posicion>0 && temp[posicion]==8) posicion--; else posicion++;      //delete if delete key pressed...
      if(posicion==BUFFER_SIZE) break;
   }while(temp[posicion-1]!=13);
   temp[posicion]='\0';
   graph.maxX=atof(temp);

   printf("Ingrese valor minimo de y: ");
   posicion=0;
   do{
      temp[posicion]=getc();
      if(posicion>0 && temp[posicion]==8) posicion--; else posicion++;      //delete if delete key pressed...
      if(posicion==BUFFER_SIZE) break;
   }while(temp[posicion-1]!=13);
   temp[posicion]='\0';
   graph.minY=atof(temp);
   
   printf("Ingrese valor maximo de y: ");
   posicion=0;
   do{
      temp[posicion]=getc();
      if(posicion>0 && temp[posicion]==8) posicion--; else posicion++;      //delete if delete key pressed...
      if(posicion==BUFFER_SIZE) break;
   }while(temp[posicion-1]!=13);
   temp[posicion]='\0';
   graph.maxY=atof(temp);

   graph.minViewX=graph.minX;
   graph.maxViewX=graph.maxX;
   graph.minViewY=graph.minY;
   graph.maxViewY=graph.maxY;

   //Calculating centers...
   graph.centerX= (graph.x2-graph.x1)/2;
   graph.centerY= (graph.y2-graph.y1)/2;

   incX=(graph.maxX-graph.minX)/50;       //set step cuantity for X axis
   incY=(graph.maxY-graph.minY)/50;       //set step cuantity for Y axis

   printf("Graficando...\r\n");

   //////////////////////////////////////////////////
   //PROCESO..............
   //comienzo del parseado de la ecuacion ingresada...
   //////////////////////////////////////////////////

   strlwr(EquIn);                        //1) PASAR EQUACION A MINUSCULAS

   //printf("Cadena en minusculas: %s\r\n",EquIn); 
                                        
   strCodificar(EquIn);                   // 2) REDUCIR ECUACION PARA OPTIMIZAR PROCESADO POSTERIOR

   printf("Cadena codificada: %s\r\n",EquIn);

   strPosFijar(EquIn,EquIn);              // 3) Pasar a notación PostFija

   printf("Cadena en notacion postfija: %s\r\n",EquIn);

   //cut unuseful zones...
   //if(graph.minX<graph.minViewX) graph.minX=graph.minViewX;
   //if(graph.maxX>graph.maxViewX) graph.maxX=graph.maxViewX;
   //if(graph.minY<graph.minViewY) graph.minY=graph.minViewY;
   //if(graph.maxY>graph.maxViewY) graph.maxY=graph.maxViewY;

/*
//Ejes!
   varx=0.0;
   varz=0.0;
   for(vary=0.0;Xp>=0;vary+=0.4){
      Xp = RAIZ2SOBRE2 * (varX - varY) + CentroX;
      Yp = -(RAIZ2TERCIOS * varZ - UNOSOBRERAIZ6 * (varX + varY)) + CentroY;
      GLCD_pixel((int8)Xp,(int8)Yp,1);
   }

   vary=0.0;
   varz=0.0;
   for(varx=0.0;Xp<Radius+CentroX;varx+=0.4){
      Xp = RAIZ2SOBRE2 * (varX - varY) + CentroX;
      Yp = -(RAIZ2TERCIOS * varZ - UNOSOBRERAIZ6 * (varX + varY)) + CentroY;
      GLCD_pixel((int8)Xp,(int8)Yp,1);
   }

   varx=0.0;
   vary=0.0;
   for(varz=0.0;Yp>0;varz+=1.0){
      Xp = RAIZ2SOBRE2 * (varX - varY) + CentroX;
      Yp = -(RAIZ2TERCIOS * varZ - UNOSOBRERAIZ6 * (varX + varY)) + CentroY;
      GLCD_pixel((int8)Xp,(int8)Yp,1);
   }
*/


/*
//2D:
for(varX=graph.minX;varX<graph.maxX;varX+=0.1){
   fltPtr=strEvaluar(EquIn,StackNum,&varX,NULL,NULL);
   printf("X: %f Y: %f\r\n",varX,*fltPtr);

   Xp=varX+graph.centerX;
   Yp=graph.centerY-(*fltPtr);

   //ensure that pixel belongs to actual graph section...else do not show it!(out of bounds)
   if(Xp>=graph.x1 && Xp<=graph.x2 && Yp>=graph.y1 && Yp<=graph.y2) GLCD_pixel((int8)Xp,(int8)Yp,1);
}

printf("HECHO!\r\n");
while(1);
*/

//Proyeccion Isométrica...
   for(varY=graph.minY;varY<graph.maxY;varY+=incY){
      for(varX=graph.minX;varX<graph.maxX;varX+=incX){
         //indicate no error...
         errno=0;
         fltPtr=strEvaluar(EquIn,StackNum,&varX,&varY,NULL);
         //if errors during calculating...do not bother at all..
         if(errno) continue;
         
         //calculate isometric proyection
         varZ = *fltPtr;
         Xp = RAIZ2SOBRE2 * (varX - varY);
         Yp = (RAIZ2TERCIOS * varZ - UNOSOBRERAIZ6 * (varX + varY));
            
         //ensure that values are inside drawing zone...
         if(Xp>=graph.minViewX && Xp<=graph.maxViewX && Yp>=graph.minViewY && Yp<=graph.maxViewY){
            //printf("X: %f Y: %f Z: %f\r\n",varX,varY,varZ);
         
            //now let´s ubicate them inside actual graphic bounds...
            Xp=(Xp-graph.minViewX)*(float32)(graph.x2-graph.x1)/(graph.maxViewX-graph.minViewX)+(float32)graph.x1;
            Yp=(float32)graph.y2-((Yp-graph.minViewY)*(float32)(graph.y2-graph.y1)/(graph.maxViewY-graph.minViewY))+(float32)graph.y1; 

            //printf("XP: %f YP: %f\r\n",Xp,Yp);
            if(Xp>=graph.x1 && Xp<=graph.x2 && Yp>=graph.y1 && Yp<=graph.y2) GLCD_pixel((int8)Xp,(int8)Yp,1);            
         }
      }
   }

   printf("Proceso de graficacion finalizado.\r\n");

/*
//polares
  for(varY=-PI/2;varY<PI/2;varY+=PI/63){
      for(varX=-PI;varX<PI;varX+=2*PI/31){
         fX=Radius*cos(varX)*cos(varY);
         fY=Radius*cos(varX)*sin(varY);
         fZ=Radius*sin(varX);

         Xp=Sqrt(2.0) / 2.0 * (fX - fY) * Distance + CentroX;
         Yp = (Sqrt(2.0 / 3.0) * fZ - (1.0 / Sqrt(6.0)) * (fX + fY)) * Distance + CentroY;
         GLCD_pixel((int8)Xp,(int8)Yp,1);
       //printf("Xp: %f Yp: %f\r\n",Xp,Yp);
      }
  }
*/  
  
 //printf("EL resultado de la ecuacion es: %9f\r\n",*fltPtr);
   while(1);
}
Пример #17
0
void main(void)
{
	setup_adc(ADC_CLOCK_DIV_8);
	setup_adc_ports(sAN0);
	set_adc_channel(0);
	setup_wdt(WDT_ON);
	setup_timer_1(T1_EXTERNAL | T1_ENABLE_SOSC);	// Set up the timekeeping timer
	setup_timer_2(T2_DIV_BY_1, 0x28, 1);		// Set up SPI clock timer
	setup_timer_3(T3_INTERNAL | T3_DIV_BY_8);	// Set up scheduler timer
	output_low(ALARM_PIN);
	enable_interrupts(INT_RDA);					// Enable serial interrupt
	enable_interrupts(INT_TIMER1);				// Enable timekeeping timer interrupt
	enable_interrupts(INT_TIMER3);				// Enable scheduler timer interrupt
	enable_interrupts(GLOBAL);					// Enable interrupts globally

	if(read_eeprom(EEPROM_RESET)==0x42)
	{
		time.hours=read_eeprom(EEPROM_HOURS);
		time.minutes=read_eeprom(EEPROM_MINUTES);
		time.seconds=read_eeprom(EEPROM_SECONDS);
#IFDEF DRINKING_GAME
		shot_count=read_eeprom(EEPROM_SHOTS);
#ENDIF
		write_eeprom(EEPROM_RESET,0x00);
	}
	else
	{
#IFDEF DRINKING_GAME
		time.seconds=0;
#ELSE
		time.seconds=(((uint8_t)timestr[6]-48)*10)+((uint8_t)timestr[7]-46);
#ENDIF
		time.minutes=(((uint8_t)timestr[3]-48)*10)+((uint8_t)timestr[4]-48);
		time.hours=(((uint8_t)timestr[0]-48)*10)+((uint8_t)timestr[1]-48);		// Parse timestr to time struct
	}
	memset(command_buffer, 0, sizeof(command_buffer));
	memset(command, 0, sizeof(command));
	
	restart_wdt();
	init_display();

	fprintf(COM1, "HELLO!\r\n");	// Say hello!

	set_timer1(-32768);			// Begin timekeeping

	t10ms=0;
	t100ms=0;
	t100ms0=0;
	t1s0=0;
	set_timer3(-20000);			// Reset and set scheduler
	while(TRUE)
	{
		restart_wdt();
		if(t10ms0==1)
		{
			t10ms0=0;
			if(command_waiting) process_command();
		}
		if(t100ms0==1)
		{
			t100ms0=0;
			update_brightness();
			if((alarm)&&(alarm_count<5))
			{
				if(alarm_count==0) output_high(ALARM_PIN);
				alarm_count++;	
			}
			else
			{
				output_low(ALARM_PIN);
				alarm=FALSE;
				alarm_count=0;
			}
		}
		if(t100ms1==5)
		{
			t100ms1=0;
		}
		if(t1s0==1)
		{
			t1s0=0;
#IFNDEF DRINKING_GAME
			toggle_colon();
#ENDIF
			update_display();
			if(manual_alarm==FALSE) wallclock_alarm();
		}
	}
}
Пример #18
0
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
Пример #19
0
void main(void)
{
  int32 count = 0;
  unsigned long int reading, average, total;
  float readingVolts;

  unsigned long int history[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

  printf("Written by David Manouchehri\n\r");

  setup_adc_ports(RA0_ANALOG);
  setup_adc(ADC_CLOCK_INTERNAL);

  set_adc_channel(0);
  delay_us(10);
  while(1)
  {
    reading = read_adc();
    readingVolts = (reading * 5.0)/255;
    delay_us(10);

    //printf("Reading is %lu = %4.2f Volts (float)\r\n", reading, readingVolts);
    
    if(readingVolts >= 3.33)
    {
      singleLED(0, 1);
      singleLED(1, 0);
      singleLED(2, 0);
    }
    else if(readingVolts >= 1.66)
    {
      singleLED(1, 1);
      singleLED(0, 0);
      singleLED(2, 0);
    }
    else
    {
      singleLED(2, 1);
      singleLED(0, 0);
      singleLED(1, 0);
    }
    
    //history[9] = 1;
    for (int i = 0; i < 10; i++)
    {
      history[i] = history[i + 1];
    }

    history[9] = reading;

    average = 0;
    for (int j = 0; j < 10; j++)
    {
      average += history[j];
      unsigned long int tempy =  history[j];
      //printf(" %lu ", tempy);
    }
    //printf(" Done\r\n");

    delaySeconds(1);
    
    printf(" %lu ", average);

    /*singleLED(5, 0); 
    singleLED(3, 1);
    delay_ms(reading);
    singleLED(3, 0);
    singleLED(4, 1);
    delay_ms(reading);
    singleLED(4, 0);
    singleLED(5, 1);
    delay_ms(reading);*/

    //delay_ms(100);
    //flipLED(0);
    //Routine stuff
    //printf("Number of runs: %ld\n\r", count);
    count++;    
    //delay_ms(100);
  }
}
Пример #20
0
void main( void )
{
    unsigned char stateSem1 = vermelho;
    unsigned char stateSem2 = verde;
    unsigned char cntTimeSem1 = 0;
    unsigned char cntTimeSem2 = 0;
    unsigned char flgEnableSem1 = 0;
    unsigned char flgEnableSem2 = 0;
    setup_adc_ports( NO_ANALOGS );
    setup_adc( ADC_OFF );
    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_DISABLED,0,1 );
    set_tris_c( 0x00 );
    //Inicializando os semáforos no estado conhecido.
    output_high( vermSem1 );
    output_high( verdeSem2 );

    while( 1 )
    {
        //máquina de estados do semáforo 1.
        switch( stateSem1 )
        {
        case vermelho:

            //Quando estiver no vermelho, se o flgEnableSem1 for verdadeiro, conto dois segundos antes de comutar para o estado verde.
            if( flgEnableSem1 == 1 )
            {
                cntTimeSem1++;

                if( cntTimeSem1 > 2 )
                {
                    cntTimeSem1 = 0;
                    stateSem1 = verde;
                    flgEnableSem1 = 0;
                    output_low( vermSem1 );
                    output_low( amarSem1 );
                    output_high( verdeSem1 );
                }
            }

            break;

        case amarelo:
            //Quando estiver no amarelo, conto 5 segundos antes de comutar para o vermelho. Observando que o estado amarelo de Sem1 habilita o flgEnableSem2, propiciando a
            //passagem de vermelho pra verde do semáforo2.
            cntTimeSem1++;

            if( cntTimeSem1 > 5 )
            {
                flgEnableSem2 = 1;
                stateSem1 = vermelho;
                cntTimeSem1 = 0;
                output_high( vermSem1 );
                output_low( amarSem1 );
                output_low( verdeSem1 );
            }

            break;

        case verde:
            //Quanto estiver no verde, aguardo 30 segundos antes e mudar para o vermelho.
            cntTimeSem1++;

            if( cntTimeSem1 > 30 )
            {
                cntTimeSem1 = 0;
                stateSem1 = amarelo;
                output_low( vermSem1 );
                output_high( amarSem1 );
                output_low( verdeSem1 );
            }

            break;
        }

        //máquina de estados do sem2
        switch( stateSem2 )
        {
            //Quando estiver no vermelho, se o flgEnableSem2 for verdadeiro, conto dois segundos antes de comutar para o estado verde.
        case vermelho:
            if( flgEnableSem2 == 1 )
            {
                cntTimeSem2++;

                if( cntTimeSem2 > 2 )
                {
                    stateSem2 = verde;
                    cntTimeSem2 = 0;
                    flgEnableSem2 = 0;
                    output_low( vermSem2 );
                    output_low( amarSem2 );
                    output_high( verdeSem2 );
                }
            }

            break;

        case amarelo:
            //Quando estiver no amarelo, conto 5 segundos antes de comutar para o vermelho. Observando que o estado amarelo de Sem1 habilita o flgEnableSem1, propiciando a
            //passagem de vermelho pra verde do semáforo1.
            cntTimeSem2++;

            if ( cntTimeSem2  > 5 )
            {
                cntTimeSem2 = 0;
                flgEnableSem1 = 1;
                stateSem2 = vermelho;
                output_high( vermSem2 );
                output_low( amarSem2 );
                output_low( verdeSem2 );
            }

            break;

        case verde:
            //Quanto estiver no verde, aguardo 30 segundos antes e mudar para o vermelho.
            cntTimeSem2++;

            if ( cntTimeSem2 > 30 )
            {
                cntTimeSem2 = 0;
                stateSem2 = amarelo;
                output_low( vermSem2 );
                output_high( amarSem2 );
                output_low( verdeSem2 );
            }

            break;
        }

        //Loop do programa será de 1segundo, que é a unidade mínima de contagem de tempo.
        delay_ms( 1000 );
    }
}
Пример #21
0
void init()
{
	// Inicializa puertos
	set_tris_a(0b11111111);
	set_tris_b(trisB_value);

	// ***ADC***
	setup_port_a(sAN0);
	setup_adc(ADC_CLOCK_INTERNAL);
	set_adc_channel(0);
	setup_adc_ports(sAN0);
	setup_vref(VREF_HIGH | 8);
	
	// Seteo el Timer1 como fuente interna
	setup_timer_1(T1_INTERNAL | T1_DIV_BY_8);
	set_timer1(26786);
	
	// Interrupcion sobre el Timer1
	enable_interrupts(INT_TIMER1);

	// Seteo el pin RB0 - Sensor de ultrasonido :)
	ext_int_edge(L_TO_H);
	enable_interrupts(INT_EXT);

	// Habilito las interrupciones
	enable_interrupts(GLOBAL);
	
	// Variable para hacer el reset
	reset = false;

	// Apaga todos los sensores
	sensor1 = SENSOR_OFF;
	sensor2 = SENSOR_OFF;
	sensor3 = SENSOR_OFF;
	sensor4 = SENSOR_OFF;
	sensor5 = SENSOR_OFF;

	// Inicializa los valores
	values[0] = 0x0000;
	values[1] = 0x0000;
	values[2] = 0x0000;
	values[3] = 0x0000;
	values[4] = 0x0000;
	values[5] = 0x0000;

	// Muestras iniciales
	samples = SAMPLES_DEFAULT;
	
	// Inicializa la mascara -> todos habilitados (0x3F)
	sensorMask = DEFAULT_MASK;
	
	//Determina el estado actual
	state = STATE_FREE;
	
	// Sin lectura temprana
	readSensor = 0x00;
	bufferedReadSensor = 0x00;
	actalTO = 0x00;
	requestFrom = 0x00;
	bufferedFrom = 0x00;
	actalCmd = 0x00;
	requestCmd = 0x00;
	bufferedCmd = 0x00;

	alarmType = 0x00;
	triggerAlarm = 0;
#if TRIGGER_TYPE == SWITCH_SENSOR
	disable_interrupts(INT_EXT);
#endif

#if TRIGGER_TYPE == LED
	// TRIGGER como escritura
	bit_clear(trisB_value, 0);
	set_tris_b(trisB_value);
#endif

	return;	
}	
Пример #22
0
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);

      }
      
      

      
   }
   }
Пример #23
0
void analog_config()          // Porto An0 analogico
{
setup_adc_ports(an0);
setup_adc(ADC_CLOCK_INTERNAL);
set_tris_a(0b00000001); 
}
Пример #24
0
void main(){
setup_oscillator (OSC_8MHZ);
setup_timer_1(T1_DISABLED);
setup_adc_ports(NO_ANALOGS|VSS_VDD);
setup_adc(ADC_OFF);
setup_comparator(NC_NC_NC_NC);
setup_vref(FALSE);

// Give indiction that the microcontroller is up and running
for (i=0;i<5;i++){
blink();
}

//On boot interactive mode is on so that the user can use a terminal interface
interactive = 1;

//Main loop starts here...
while(true){  //Waits for a command to come in over the serial port in interactive mode   
if (interactive == 1)
   printf("Please enter a command (h for help):\n\r");

command = getc();

switch (command){
case 'i':  //Turn off interactive mode
   printf("Turning Off Interactive...\n\r");
   interactive = 0;
   printf("Done...\n\r");
   break;
   
case 'r':  //Reset DS2482
   if (interactive == 1){
      printf("Resetting the DS2482\n\r");
   }
   //Do the Reset
   result = ds2482_reset();
   
   if (interactive == 1){
      if (result == 1)
         printf("...Success...\n\r");
      else printf ("...Fail..\n\r");
   }
   break;
   
case 'c':  //Configure DS2482
//Active pullup should always be selected unless
//there is only a single slave on the 1-Wire line.
//0x01 1WS Disabled, SPU Disabled, 0 NC, APU Active Pullup (Normal Operation for more then one device on onewire bus)
//0x05 1WS Disabled, SPU Active, 0 NC, APU Active Pullup (Strong pullup is commonly used with 1-Wire parasitically powered temperature sensors, eeprom, A/D converters)

   if (interactive == 1){
      printf("Configuring the DS2482\n\r");
   }
   
   //Do the Config
   result = ds2482_write_config(0x01);
   
   if (interactive == 1){
      if (result == 1)
         printf("...Success...\n\r");
      else printf ("...Fail..\n\r");
   }
   break;
   
case 'R':  //Reset One Wire Bus
   if (interactive == 1){
      printf("Resetting the One Wire\n\r");
   }
   
   result = OWreset();
   
   if (interactive == 1){
      if (result == 1)
         printf("...Success...\n\r");
      else printf ("...Fail..\n\r");
   }
   break;
   
case 'n': //Read the Network Address
OWreset();
delay_ms(1);
OWWriteByte("33");
//delay_ms(20);

for(i=0; i<=7; i++) {
result = OWReadByte();
printf ("%2X",result);
delay_ms(1);
}

break;

case 's': //Read the OW status register
OWreset();
delay_ms(1);
OWWriteByte(204);  //Transmit skip Rom Command CC = 204
OWWriteByte(105);  //0x69 Transmit Read RAM command
OWWriteByte(1); //Transmit Read start address
result=OWReadByte();

break;
  


case 'f': //Fix the floating power switch

OWreset();
OWWriteByte(0xCC);
OWWriteByte(0x6C);    //Write Data Command
OWWriteByte(0x31);    //Eeprom address but actually gets written to Shadow Ram
OWWriteByte(0xE7);    //Value to make PMOD1 SWEN=0 RNAOP=0

//Copy the shadow Ram written above over to actual EEPROM
OWreset();
OWWriteByte(0xCC);
OWWriteByte(0x48);    //send the copy command
OWWriteByte(0x30);    //copy shadow ram to the block containing 31

break;   
   
   
   
default:  //Displays help message if you get an 'h' or an unknown command
   printf("PyroLogger Board Found and Responding...\n\r");
   printf("Firmware Version 2\n\r");
   printf("Interactive Mode is ON\n\r");
   printf("\n\r");
   printf("\n\r");
   printf("Command List:\n\r");
   printf("h = System Help\n\r");
   printf("i = Exit ineractive mode\n\r");
   printf("r = Reset DS2482\n\r");
   printf("c = Configure DS2482\n\r");
   printf("R = Reset One Wire Bus\n\r");
   printf("N = Print Net Address\n\r");
  
}

}
}
Пример #25
0
void main( void )
{
    unsigned long int duracaoAlarme = 0;
    setup_adc_ports( NO_ANALOGS );
    set_tris_b( 0b01110000 );
    set_tris_c( 0x00 );
    set_tris_d( 0x00 );
    portc = 0;
    portd = 0;
    //Habilito os displays
    output_high( PIN_B3 );
    output_high( PIN_B2 );
    //Faço o setup do timer1 para clock interno e com prescaler de 8. A base de tempo é de 1/( 20MHz/4/8 )= 1.6uS
    setup_timer_1( T1_INTERNAL | T1_DIV_BY_8 );
    //Carrego o timer com 34285 de forma que ele conte ( 65535 - 34285 ) = 31250*1.6uS = 50ms.
    set_timer1( 34285 );
    //Habilito as interrupções do timer1 e da porta b
    enable_interrupts( global );
    enable_interrupts( int_timer1 );
    enable_interrupts( int_rb );

    while( 1 )
    {
        switch( Clock.flgs.mode )
        {
        case 0:
            //Modo 0: Atualizo a hora no display e verifico a ocorrência do alarme. Caso esteja na hora de alarme,
            //faço o led de alarme piscar a cada 1 segundo durante 1 minuto.
            output_high( PIN_B2 );
            output_high( PIN_B3 );
            driverDisplay( &Clock.time );

            if( Clock.time.hora == Clock.alarmTime.hora )
            {
                if( Clock.time.minuto == Clock.alarmTime.minuto )
                {
                    Clock.flgs.alarme = 1;
                }
            }

            if( Clock.flgs.alarme )
            {
                duracaoAlarme++;

                if( !( duracaoAlarme%100 ) )
                {
                    portb^=0x02;
                }
                else if( duracaoAlarme > 6000 )
                {
                    duracaoAlarme = 0;
                    Clock.flgs.alarme = 0;
                    output_high( PIN_B1 );
                }
            }

            break;

            //Modo 1: Setando hora
        case 1:
            setHora( &Clock.time );
            break;

            //Modo 2: Setando minuto
        case 2:
            setMinuto( &Clock.time );
            break;

            //Modo 3: Setando hora do alarme
        case 3:
            setHora( &Clock.alarmTime );
            break;

            //Modo 4: Setando minuto do alarme
        case 4:
            setMinuto( &Clock.alarmTime );
            break;
        }

        //meu loop terá 10ms
        delay_ms( 10 );
    }
}
Пример #26
0
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;



      }

   }
}

}
Пример #27
0
void main()
{
   struct rx_stat rxstat;
   int32 rx_id;
   int in_data[8];
   int rx_len;

   int out_data[8];
   int16 tmp;
   int32 tx_id;
   int1 tx_rtr=0;
   int1 tx_ext=0;
   int tx_len=8;
   int tx_pri=3;

   // bitmap, expanded to 8 bit (needed?)
   int8 sequence[MAX_CHANNELS];
   int32 val;

   int i;
   for (i = 0; i < MAX_CHANNELS; i++)
      sequence[i] = MAX_CHANNELS;

   // resource initialization.
   setup_adc_ports(AN0);
   setup_adc(ADC_CLOCK_INTERNAL);
   setup_spi(FALSE);
   setup_wdt(WDT_OFF);
   setup_timer_0(RTCC_INTERNAL);

   setup_timer_1(T1_DISABLED);
   //setup_timer_1(T1_INTERNAL|T1_DIV_BY_1);
   //set_timer1(16000);

   setup_timer_2(T2_DISABLED,0,1);
   setup_timer_3(T3_DISABLED|T3_DIV_BY_1);

   _board_ID = read_eeprom(0);

   can_init();
   adc_init();

   enable_interrupts(INT_TIMER1);
   enable_interrupts(GLOBAL);

   while(TRUE)
   {
      if (can_kbhit() || _wait)   // wait for a message on the CAN bus
      {
         // handles timer message
         if (_wait)
         {
            _wait = 0;

            for (i = 0; i <= MAX_CHANNELS-3; i+=3)
            {
               if (sequence[i] < MAX_CHANNELS)
                  tmp = read_analog(i);
               else
                  tmp = 0;

               out_data[1] = (int8)(tmp);
               out_data[2] = (int8)(tmp>>8);

               if (sequence[i+1] < MAX_CHANNELS)
                  tmp = read_analog(i+1);
               else
                  tmp = 0;

               out_data[3] = (int8)(tmp);
               out_data[4] = (int8)(tmp>>8);

               if (sequence[i+2] < MAX_CHANNELS)
                  tmp = read_analog(i+2);
               else
                  tmp = 0;

               out_data[5] = (int8)(tmp);
               out_data[6] = (int8)(tmp>>8);

               while (!can_tbe()) ;

               tx_id = ID_BASE;
               tx_id |= ((_board_ID) << 4);
               //tx_id |= ((0 & 0x00f0) >> 4);

               out_data[0] = 0x30+i;
               tx_len = 7;

               can_putd(tx_id, out_data, tx_len, tx_pri, tx_ext, tx_rtr);
            }

            // last message.
            if (sequence[30] < MAX_CHANNELS)
               tmp = read_analog(30);
            else
               tmp = 0;

            out_data[1] = (int8)(tmp);
            out_data[2] = (int8)(tmp>>8);

            if (sequence[31] < MAX_CHANNELS)
               tmp = read_analog(31);
            else
               tmp = 0;

            out_data[3] = (int8)(tmp);
            out_data[4] = (int8)(tmp>>8);

            while (!can_tbe()) ;

            tx_id = ID_BASE;
            tx_id |= ((_board_ID) << 4);
            //tx_id |= ((0 & 0x00f0) >> 4);

            out_data[0] = 0x30+30;
            tx_len = 5;

            can_putd(tx_id, out_data, tx_len, tx_pri, tx_ext, tx_rtr);
         }

         if (can_getd(rx_id, &in_data[0], rx_len, rxstat))
         {
            // handles message for the analog channel
            if ((rx_len == 1) && ((rx_id & 0x700) == 0x200) && (in_data[0] < MAX_CHANNELS))
            {
  		 	      tmp = read_analog(in_data[0]);
               out_data[1] = (int8)(tmp);
               out_data[2] = (int8)(tmp>>8);

               while (!can_tbe()) ;

               tx_id = ID_BASE;
               tx_id |= ((_board_ID) << 4);
               tx_id |= ((rx_id & 0x00f0) >> 4);

               out_data[0] = in_data[0];
			      tx_len = 3;

               // replies to message.
               can_putd(tx_id, out_data, tx_len, tx_pri, tx_ext, tx_rtr);
            }
            // handles message to prepare a sequence (32).
            else
            if ((rx_len == 5) && ((rx_id & 0x700) == 0x200) && (in_data[0] == MAX_CHANNELS))
            {
               for (i = 0; i < MAX_CHANNELS; i++)
                  sequence[i] = MAX_CHANNELS;

               // perhaps this is not needed.
               while (!can_tbe()) ;

               tx_id = ID_BASE;
               tx_id |= ((_board_ID) << 4);
               tx_id |= ((rx_id & 0x00f0) >> 4);

               out_data[0] = in_data[0];
			      tx_len = 1;

               setup_timer_1(T1_DISABLED);

               // replies to message.
               can_putd(tx_id, out_data, tx_len, tx_pri, tx_ext, tx_rtr);
            }
            // handles message to prepare a broadcast sequence (33).
            else
            if ((rx_len == 5) && ((rx_id & 0x700) == 0x200) && (in_data[0] == MAX_CHANNELS+1))
            {
               for (i = 0; i < MAX_CHANNELS; i++)
               {
                  val = *((int32 *)(&in_data[1]));
                  if (val & 0x00000001)
                  {
                     sequence[MAX_CHANNELS-1-i] = MAX_CHANNELS-1-i;
                  }
                  else
                  {
                     sequence[MAX_CHANNELS-1-i] = MAX_CHANNELS;
                  }
                  val >>= 1;
               }

               // perhaps this is not needed.
               // LATER: check the driver.
               while (!can_tbe()) ;

               tx_id = ID_BASE;
               tx_id |= ((_board_ID) << 4);
               tx_id |= ((rx_id & 0x00f0) >> 4);

               out_data[0] = in_data[0];
			      tx_len = 1;

               val = *((int32 *)(&in_data[1]));
               if (val == 0)
               {
                  setup_timer_1(T1_DISABLED);
               }
               else
               {
                  setup_timer_1(T1_INTERNAL|T1_DIV_BY_8);
                  set_timer1(65536-5000);
               }

               // replies to message.
               can_putd(tx_id, out_data, tx_len, tx_pri, tx_ext, tx_rtr);
            }
            // handles CAN bus messages for the downloader
            else
            if ((rx_len == 1) &&  (((rx_id>>8) & 0x7)==7))
Пример #28
0
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;
         
      }
   }
}
void main(void) {

   int8 recibe[3];                  //declaramos variables
   int8 envia[1];

   setup_adc_ports( ALL_ANALOG );		//Configuramos el puerto a como analogo
   setup_adc( ADC_CLOCK_INTERNAL );
   set_adc_channel( 0 );  

   LED_OFF(LEDV);                   //encendemos led rojo
   LED_ON(LEDR);

   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

  LED_OFF(LEDR);
  LED_ON(LEDV);                    //encendemos led verde
    
  /* while(TRUE){
       envia[0] = (int8)Read_ADC();
       if (envia[0] > 0x7F){
              LED_ON(LEDR);
              LED_ON(LEDV);                    //encendemos led verde
         }else{
              LED_OFF(LEDR);
              LED_OFF(LEDV);  //otra acción
        }
   } 
*/
   while (TRUE)
   {
      if(usb_enumerated())          //si el PicUSB está configurado
      {
         if (usb_kbhit(1))          //si el endpoint de salida contiene datos del host
         {
            usb_get_packet(1, recibe, 3); //cojemos el paquete de tamaño 3bytes del EP1 y almacenamos en recibe

            if (modo == 0) // Modo_Suma
            {
              envia[0] = (int8)Read_ADC();
              usb_put_packet(1, envia, 1, USB_DTS_TOGGLE); //enviamos el paquete de tamaño 1byte del EP1 al PC
				if (envia[0] > 0x7F){
              LED_ON(LEDR);
              LED_ON(LEDV);                    //encendemos led verde
         	}else{
              LED_OFF(LEDR);
              LED_OFF(LEDV);  //otra acción
        }
            }

            if (modo == 1) // Modo_Led
            {
               if (param1 == 0) {LED_OFF(LEDV); LED_OFF(LEDR);} //apagamos los leds
               if (param1 == 1) {LED_ON(LEDV); LED_OFF(LEDR);} //encendemos led verde
               if (param1 == 2) {LED_OFF(LEDV); LED_ON(LEDR);} //encendemos led rojo
            }
         }
      }
   }
}
void main(void) {
     
   int8 recibe[5];                  //declaramos variables
   int8 send2[1];

   LED_OFF(LED_OK);                   //encendemos led rojo
   LED_ON(LED_FAIL);
            
   usb_init();                      //inicializamos el USB  
   
   setup_adc_ports(AN0);         //Configura canais analógico
   setup_adc(ADC_CLOCK_INTERNAL);    //De acordo com relógio interno.
   
   /*SETUP_TIMER_1 (T1_INTERNAL|T1_DIV_BY_2);       //Configurar timer1 para clock iterno/8
   enable_interrupts (INT_TIMER1);                //Habilitar Interrupções
   enable_interrupts (global);*/

   usb_task();                      //habilita periferico usb e interrupciones
   usb_wait_for_enumeration();      //esperamos hasta que el PicUSB sea configurado por el host
   
   enable_interrupts (global);

   LED_OFF(LED_FAIL);                 //desligo o LED vermelho
   LED_ON(LED_OK);                    //acendo o LED verde
   
   move_x('S');
   move_y('S');
         
   while (true)
   {
      if(usb_enumerated())          //si el PicUSB está configurado
      {  
         if (usb_kbhit(1))          //si el endpoint de salida contiene datos del host
         {            
            LED_ON(LED_DATA);
            usb_get_packet(1, recibe, 5); //cojemos el paquete de tamaño 3bytes del EP1 y almacenamos en recibe            
            
            if(modo == 1)
            {               
                  if(dir_x == 1 && value_x == 1){
                     move_x('R');
                  }
                  if(dir_x == 2 && value_x == 1){
                     move_x('L');
                  }                  
                  if(dir_y == 1 && value_y == 1){
                     move_y('F');
                  }
                  if(dir_y == 2 && value_y == 1){
                     move_y('B');
                  }
                  
                  delay_ms(20);               
            }
            
            if (modo == 4)
            {
               status = 1;
               usb_put_packet(1, send2, 1, USB_DTS_TOGGLE); //enviada a informação para o PC com o status
            }    
            LED_OFF(LED_DATA);
         }
      }
   }
}