TODOPIC

Microcontroladores PIC => Pic32 => Mensaje iniciado por: IngRandall en 13 de Noviembre de 2012, 19:02:44

Título: Uart por software
Publicado por: IngRandall en 13 de Noviembre de 2012, 19:02:44
Hola amigos, la verdad no me acuerdo si ya se ha hablado de esto aquí, pero coloco el código del uart por software para un PIC32MX795F512L

Código: [Seleccionar]
#define GetSystemClock() (80000000ul) // Hz
#define GetInstructionClock() (GetSystemClock()/1) // Normally GetSystemClock()/4 for PIC18, GetSystemClock()/2 for PIC24/dsPIC, and GetSystemClock()/1 for PIC32.  Might need changing if using Doze modes.
#define GetPeripheralClock() (GetSystemClock()/1) // Normally GetSystemClock()/4 for PIC18, GetSystemClock()/2 for PIC24/dsPIC, and GetSystemClock()/1 for PIC32.  Divisor may be different if using a PIC32 since it's configurable.

#define RS485_RX_TRIS (TRISGbits.TRISG6)
#define RS485_RX                (_RG6)
#define RS485_TX_TRIS (TRISGbits.TRISG7)
#define RS485_TX                (_LATG7)

 void DelayMs(WORD ms)
{
    unsigned char i;
    while(ms--)
    {
        i=4;
        while(i--)
        {
            Delay10us(25);
        }
    }
}

 void Delay10us(DWORD dwCount)
{
volatile DWORD _dcnt;

_dcnt = dwCount*((DWORD)(0.00001/(1.0/GetInstructionClock())/10));
while(_dcnt--)
{
#if defined(__C32__)
Nop();
Nop();
Nop();
#endif
}
}

char RS485_RXchar(void){
    char c=0;char j=0;char i=0;
    while(RS485_RX);
    c=0;j=1;i=0;
    Delay10us(10);
    for(i=0;i<8;i++){
        Delay10us(10);     //delay_104us BaudRate de 9600
        if (RS485_RX==1){c=c+j;}
        j=j+j;
    }
    Delay10us(5);
    while(!RS485_RX);
    return c;
}

void RS485_TXchar(char c){
    char j=1,i=0;
    Delay10us(10);
    RS485_TX=0;Delay10us(10);
        for(i=0;i<8;i++){
        if(c&j){RS485_TX=1;}else{RS485_TX=0;}
        Delay10us(10);
        j=j+j;
    }
    RS485_TX=0;
    Delay10us(10);
    RS485_TX=1;
    DelayMs(1);DelayMs(1);
}

int main (void){
   RS485_RX_TRIS=1;
   RS485_TX_TRIS=0;

  char temp=0;
  while(1){
     temp=RS485_RXchar();
     if(temp!=0){RS485_TXchar(temp);}
     DelayMs(10);
  }
}

A mi me funciona, ojala a ustedes también... si hace falta algo me avisan.