Comunicação entre o PIC18F4620 e o PIC16F913

Software e Hardware para uC PIC

Moderadores: andre_luis, 51, guest2003, Renie

Comunicação entre o PIC18F4620 e o PIC16F913

Mensagempor Daniel dos Santos Costa » 16 Abr 2012 16:01

Olá

Estou tendo problemas para se comunicar entre um PIC18F4620 e um PIC16F913 via serial utilizando a biblioteca usart.h C18. O PIC18F4620 deve enviar um comando ASCII para o PIC16F913 que gerencia o módulo HRMI, sendo este ultimo um modulo que recebe dados duma cinta POLAR, e o PIC16F913 envia dados de ritmo cardíaco para o PIC18F4620 que grava os dados no cartão de memoria. No entanto, não recebo os dados para gravar no cartão de memória SD, porque o arquivo txt esta vazio. Estou anexando a página de código para poder ajudar.

Obrigado

Código: Selecionar todos
#include<p18f4620.h>
#include <stdio.h>
#include <adc.h>
#include <usart.h>
#include <delays.h>
#include <timers.h>
#include "FSIO.h"
#include "lcd_4b.h"
//#pragma config OSC=HSPLL
#pragma config OSC=HS
#pragma config IESO=OFF
#pragma config PWRT=ON
#pragma config WDT=OFF
#pragma config MCLRE=ON
#pragma config XINST=OFF
#pragma config DEBUG=OFF
#pragma config FCMEN=OFF
#pragma config LVP=OFF
#pragma config BOREN=OFF
#pragma config PBADEN=OFF


char MyBuffer[100] = "Ambience Data";
char Dia,Mes,Hora,Minuto,Segundo;
int Ano;
char card = 1;
char protected = 0;
char grav = 1;
char erro = 0;
char buff[16];


unsigned char One_Sec_Flag;
void timer_ISR(void);


// Define the high interrupt vector to be at 0x08
#pragma code high_vector=0x08 // Following code at void address 0x08
interrupt(void)
{
_asm GOTO timer_ISR _endasm  // Jump to ISR
}
#pragma code     // Return to default code section
// timer_ISR is an interrupt service routine (jumps here every 5ms)
#pragma interrupt timer_ISR
void timer_ISR( )
{
One_Sec_Flag = 1;     // Set One_Sec_Flag
TMR0L = 0xEE;      // Re-load TMR0
TMR0H = 0x85;      // Re-Load TMR0H
//WriteTimer0(26473);
INTCON = 0x20;      // Set T0IE and clear T0IF
}
// Configure Timer for 1 second interrupts. Load TIMER registers with
// 16 bit value 26473 = 0x6769
void Config_Timer(void)
{
// OpenTimer0( TIMER_INT_OFF &
//    T0_16BIT &
//    T0_SOURCE_INT &
//    T0_PS_1_256 );
T0CON = 0x87; // 16 bit,Prescaler = 256
TMR0L = 0xEE; // Load TMR0L=0x69
TMR0H = 0x85; // Load TMR0H=0x67
//WriteTimer0(26473);
INTCON = 0xA0; // Enable TMR0 interrupt
}


// This function initializes the USART
void Init_USART(void)
{
 OpenUSART(USART_TX_INT_OFF & // Interrupção de transmissão desabilitada
 USART_RX_INT_OFF &    // Interrução de recepção desabilitada
 USART_ASYNCH_MODE &    // Modo assíncrono
 USART_EIGHT_BIT &    // Dados de 8 bits
 USART_CONT_RX &     //
 USART_BRGH_LOW,     // Alta velocidade
 51);       // Baud rate de 9600
}


////////////////////////////////////////////////////////////////////////////
// This function opens the A/D converter, reads analog data, converts into//
// digital and then returns. The required channel number is passed as an  //
// argument to the function                                               //
////////////////////////////////////////////////////////////////////////////
int Read_ADC_Chan(unsigned char chan)
{
 int Res;
 OpenADC(ADC_FOSC_64 &   // Open the A/D
   ADC_RIGHT_JUST & // Resultado nos bits menos significativos
   ADC_0_TAD,   // Tempo de aquisição manual
   ADC_CH1 &   // Seleciona o canal 1 (AN1)
   ADC_INT_OFF &  // Interrupção desabilitada
   ADC_VREFPLUS_VDD & // Vref+ = VDD
   ADC_VREFMINUS_VSS, // Vref- = VSS
   13);    // Habilita AN0 a AN12 como analógica
 Delay10TCYx(10);  // Delay for 100 cycles
 SetChanADC(chan);  // Select channel
 ConvertADC( );   // Convert
 while(BusyADC( ));  // Wait until complete
 Res = ReadADC( );  // Read analog data
 CloseADC( );   // Close A/D
 return Res;   // Return the result
}


//////////////////////////////////////////////////////////////////////////////
// Esta função detecta a existência do cartão de memoria no soquete além da //
// proteção esta ativada ou não.                                            //
//////////////////////////////////////////////////////////////////////////////
void verifica_cartao(void)
{
 if (PORTBbits.RB2 == 0)
 {
  if (!card)
  {
   lcd_posicao(1,7);
   sprintf(buff,"YES       ");
   lcd_escreve(buff);
   card = 1;
  }
 }
 else
 {
  if (card)
  {
   lcd_posicao(1,7);
   sprintf(buff,"NO        ");
   lcd_escreve(buff);
   card = 0;
  }
 }
 if (PORTBbits.RB3 == 0)
 {
  if (protected)
  {
   lcd_posicao(2,12);
   sprintf(buff,"NO   ");
   lcd_escreve(buff);
   protected = 0;
  }
 }
  else
  {
   if (!protected)
   {
    lcd_posicao(2,12);
    sprintf(buff,"YES  ");
    lcd_escreve(buff);
    protected = 1;
   }
  }
}


void grava_cartao(void)
{
 FSFILE *MyFile1, *MyFile2, *MyFile3;
 char nome[20], mode[3];
 unsigned char err, k;
 char *Sc;
 int result, i, j;
 float mV, Temp, Temp_Bla;
 char Heart[3];
 k= 0;
 // Configure Timer. Start timer interrupts
 Config_Timer( );
 do
 {
  Delay10KTCYx(50);
  err = FSInit();
  k++;
 }
 while ((k<10) && (err==FALSE));
 if ((k==10) && (err==FALSE))
 {
  TRISDbits.TRISD0 = 0;
  PORTDbits.RD0 = 1;            //Error...
  erro = 1;
  }
 else
 {
  //TRISDbits.TRISD1 = 0;
  //PORTDbits.RD1 = 1;
  sprintf(&nome[0],"Temp_Amb.txt");
  sprintf(&mode,"w+");
  MyFile1 = FSfopen(nome,mode);
  sprintf(&nome[0],"Temp_Bla.txt");
  sprintf(&mode,"w+");
  MyFile2 = FSfopen(nome,mode);
  sprintf(&nome[0],"Humi.txt");
  sprintf(&mode,"w+");
  MyFile3 = FSfopen(nome,mode);
   
  for(Sc=&MyBuffer[0];*Sc!=0;Sc++);
  k=Sc-&MyBuffer[0];
  Dia=02;Mes=02;Ano=2012;Hora=14;Minuto=29;Segundo=10;
  SetClockVars(Ano,Mes,Dia,Hora,Minuto,Segundo);
  FSfwrite(&MyBuffer[0],1,k,MyFile1);
  FSfwrite(&MyBuffer[0],1,k,MyFile2);
  FSfwrite(&MyBuffer[0],1,k,MyFile3);
  while(1)
  {
   result = Read_ADC_Chan(ADC_CH1); // Get the data
   mV = (result * 500) / 1023;   // Convert to mV
   Temp = mV;        // Calculate temperature
   i = (int)Temp;       // Integer part
   j = (int)((Temp-i)*10);    // Fractional part
   // Write to SD card
   FSfprintf(MyFile1, "\n%d.%d", i, j);
   while(BusyUSART( ));
   putcUSART('G');
   while(BusyUSART( ));
   putcUSART('1');
   while(BusyUSART( ));
   putcUSART(0x0D);
   //putcUSART('\r');
   
     if (DataRdyUSART( ))
   { 
       for (i=0; i<3; i++)
         Heart = getcUSART();
       //return(0); 
   }
   // Write to SD card
   FSfprintf(MyFile2, "\n%c", Heart);
   

   if(PORTAbits.RA4 == 0)
   {
    FSfclose(MyFile1);
    FSfclose(MyFile2);
    FSfclose(MyFile3);
    break;
   }
   // Wait for a second. Variable "flag" is set whevenever an interrupt occurs
   while(!One_Sec_Flag);
   One_Sec_Flag = 0;
  } 
 }
}


void main(void)
{
 char i;
 ADCON1 = 0x0E; //VERIFICAR A NECESSIDADE DESSA LINHA!
 TRISDbits.TRISD0 = 0; // LED RED
 TRISDbits.TRISD1 = 0; // LED YELLOW
 TRISDbits.TRISD2 = 0; // LED GREEN   
 TRISAbits.TRISA4 = 1; // Chave B1
 PORTD = 0;     
 Init_USART( );    // This function initializes the USART
 lcd_inicio();   // This function initializes the Display LCD
 sprintf(buff,"\f  MONITORATION  ");
 lcd_escreve(buff);
 sprintf(buff,"\n     ANIMAL     ");
 lcd_escreve(buff);
 PORTDbits.RD0 = 1;  // LED
 //Provoca atraso de 2 segundos
 for (i = 0; i < 8; i++)
  Delay10KTCYx(250); //Atraso de 250ms * 8 = 2 seg.
 while(1)
 {
  if (grav==1)
  {
   sprintf(buff,"\fCARD:           ");
   lcd_escreve(buff);
   sprintf(buff,"\nPROTECTED:      ");
   lcd_escreve(buff);
   grav = 0;
   PORTD = 0;
   PORTDbits.RD1 = 1; // LED
   erro = 0;
  }
   
  verifica_cartao();
  if (PORTAbits.RA4 == 0)
  {
   sprintf(buff,"\****uarde, grav.  ");
   lcd_escreve(buff);
   sprintf(buff,"\nem andamento.   ");
   lcd_escreve(buff);
   PORTD = 0;
   PORTDbits.RD2 = 1; // LED   
   grava_cartao();
   Delay10KTCYx(250);   //Atraso de 250ms * 8 = 2 seg.
   if (erro)
    sprintf(buff,"\fGRAV: Erro      ");
   else
    sprintf(buff,"\fGRAV: OK         ");
    lcd_escreve(buff);
    sprintf(buff,"\nRetire o cartao.");
    lcd_escreve(buff);
    while (PORTBbits.RB2==0);
    grav = 1;
  }
 }
}
 

A subrotina grava_cartao(); que crei estar o problema principalmente na parte que recebe os dados do PIC16F913.
Daniel dos Santos Costa
Bit
 
Mensagens: 14
Registrado em: 20 Out 2011 16:11

Re: Comunicação entre o PIC18F4620 e o PIC16F913

Mensagempor andre_luis » 18 Abr 2012 07:34

Voce deve separar os testes, para saber se o problema está na gravação, ou no recebimento.
Faça um programa simples, utilize um LED para sinalizar o recebimento, e somente a partir daí, insere as rotinas de gravação.


+++
"Por maior que seja o buraco em que você se encontra, relaxe, porque ainda não há terra em cima."
Avatar do usuário
andre_luis
Dword
 
Mensagens: 5447
Registrado em: 11 Out 2006 18:27
Localização: Brasil - RJ

Mensagempor Daniel dos Santos Costa » 02 Mai 2012 08:33

Ola pessoal

Consegui resolver o problema

Muito obrigado pelo apoio

Daniel
Daniel dos Santos Costa
Bit
 
Mensagens: 14
Registrado em: 20 Out 2011 16:11


Voltar para PIC

Quem está online

Usuários navegando neste fórum: Nenhum usuário registrado e 1 visitante

x