Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

EUSART Test code for PIC18F45K22 in C language

Status
Not open for further replies.

VoltVolt

Junior Member level 1
Junior Member level 1
Joined
Sep 15, 2013
Messages
15
Helped
0
Reputation
0
Reaction score
0
Trophy points
1
Visit site
Activity points
124
Anyone can share his/her UART sample code for PIC18F45K22 (in C language)?
Just want to test whether the hyper terminal and PIC working?
I'm using Cytron UC00B USB to UART converter...

Thanks... :)
 

Code:
#include<stdio.h>
#include<p18f46k22.h>
#include "usart.h"

//#define USE_OR_MASKS

unsigned char Rxdata[8];
unsigned char Txdata[] = "test";
void delay(unsigned int i)
{
	
	for(;i>1;i--);
}
void main(void)
{
    unsigned char config=0,spbrg=0,baudconfig=0,i=0,j='a';
	OSCCONbits.IRCF0 =1;
	OSCCONbits.IRCF1 = 1;
	OSCCONbits.IRCF2 = 1;
	OSCTUNEbits.PLLEN = 1;

    ANSELA = 0x00;
    ANSELB = 0x00;
    ANSELC = 0x00;
    ANSELD = 0x00;
    ANSELE = 0x00;
    
	TRISA=0x00;
	TRISB=0X0000;	//output
    TRISC=0Xffff;	//output
    TRISD=0X00;	//output
    TRISE=0X00;	//output
    
    Close1USART();  //turn off usart if was previously on

//-----configure USART -----
    config = USART_TX_INT_OFF | USART_RX_INT_OFF | USART_ASYNCH_MODE | USART_EIGHT_BIT | USART_SINGLE_RX | USART_BRGH_LOW;
//-----SPBRG needs to be changed depending upon oscillator frequency-------
    spbrg = 51;                    //At 8Mhz of oscillator frequency & baud rate of 2400.

    Open1USART(config, spbrg);        //API configures USART for desired parameters

    baudconfig =  BAUD_8_BIT_RATE | BAUD_AUTO_OFF;
    baud1USART (baudconfig);

//------USART Transmission ----
    while(Busy1USART());             //Check if Usart is busy or not
    puts1USART((char *)Txdata);                //transmit the string



    Close1USART();
    while(1);                        //end of program

}

Do you mean this?
Where to find usart.h code?
 

hello,

if this code can help you, even in C18..
tested in real world ! not simulator.
If you want a reliable RS232 link, you MUST use a buffer and UART interrupt treatment..as in this example
and maybe survey the ErrComm counter ...

Code:
//18 sept 2013
//03/07/2012
// Pickit3 
// TESTE OK  en lecture
// attention: use radix decimal !!
// C18 MPLAB
// directory : _C18\MesProjets_C18\_18F46K22
// Projet :_C18\MesProjets_C18\_18F46K22\18F46K22_test_RS232.mcp
// Source : 18F26K22_test_RS232.c

/*
========== HARDWARE ====================
27 pf  Q=10Mhz 27pF
Interface DS275 pour liaison UART TTL <-> RS232 


PIC 18F26K22  28 pins DIP
PortB
 RB0   21   input
 RB1   22
 RB2   23   
 RB3   24   
 RB4   25 
 RB5   26  
 RB6   27  ICSP_Clck   Bleu fonce    Pin5 Pickit2 
 RB7   28  ICSP_Data   Bleu clair    Pin4 Pickit2 

       
PORTA
 RA0   2  Analog Input for AC line meaurement
 RA1   3  
 RA2   4 
 RA3   5 
 RA4   6  Output .. Led .. 390 ohms +5V
 RA5   7  Output
 RA6   8  ----- Quartz 10Mhz   C=22pF -- Gnd
 RA7   9  ------ Quartz ---    C=22pF -- Gnd

PORTC
 RC0   11
 RC1   12
 RC2   13
 RC3   14 
 RC4   15  SCL I2C  LCD4x20
 RC5   16  SDA I2C  LCD4x20                                      depend si DTE ou DCE 
 RC6   17  TX  UART1 --Blc---  3 de DS275 7 -- blanc ----> 2HE10 -nappe --DB9M DB9F cable RS232 PC
 RC7   18  RX  UART1 --rouge-  1 de DS275 5 ---bleu Fce -< 3HE10 -nappe --DB9M DB9F cable RS232 PC 
           Gnd ------------------------------------------>5 HE10 -nappe ---DB9M DB9F cable RS232 PC 


      1   --- jaune -- VPP/MCLR ---  pin1 Pickit2
      8  ---- blanc ------Gnd-----  pin3 Pickit2
 VSS  8   ----  GND Power
 VSS  19  ----  GND Power
 VDD  20  ----  +5V Power

 */

#include "p18f26k22.h"
#define p18f26k22
#define Versus "Versus 130917 C18   "

#include "stdio.h"
#include <stdlib.h>
#include <delays.h>
#include <string.h>
#include <usart.h>   // pour fonctions UART HARDWARE
#include <adc.h>
#include <ctype.h>
#include <portb.h>
#include <timers.h>
#include <math.h>

// configuration bits set in code !
// voir Help
//  Topics
//        Pic18
//            config bits settings
//                    choisir PIC18F26K22
#ifdef OSCILLATEUR_INTERNE
#pragma config FOSC = INTIO67, FCMEN = OFF, PLLCFG=OFF            // CONFIG1H
#else
#pragma config FOSC = HSMP, PLLCFG=OFF, PRICLKEN=ON ,FCMEN=OFF      // quartz 10Mhz
#endif
#pragma config IESO=OFF,PWRTEN=OFF,BOREN=OFF,WDTEN=OFF,CCP2MX=PORTC1
#pragma config PBADEN=OFF,T3CMX=PORTC0,P2BMX=PORTC0,CCP3MX=PORTB5
#pragma config MCLRE=EXTMCLR,STVREN=OFF,LVP=ON,XINST=OFF,DEBUG=OFF
#pragma config CP0 = OFF, CP1 = OFF, CP2 = OFF, CP3 = OFF                    // CONFIG5L
#pragma config CPB = OFF, CPD = OFF                                          // CONFIG5H
#pragma config WRT0 = OFF, WRT1 = OFF, WRT2 = OFF, WRT3 = OFF                // CONFIG6L
#pragma config WRTB = OFF, WRTC = OFF, WRTD = OFF                            // CONFIG6H
#pragma config EBTR0 = OFF, EBTR1 = OFF, EBTR2 = OFF, EBTR3 = OFF            // CONFIG7L
#pragma config EBTRB = OFF                                                   // CONFIG7H


// config vue sur Pickit3 : 2200 3C18 9900 0084 C00F E00F 400F

#ifndef Byte
#define Byte unsigned char
#endif

// Using Q=10Mhz  Clock 
#define CLOCK_FREQ 10000000L 
#define FOSC 10000000

#define DureeCycle 10 // * 1 diziemes de secondes => 1,0sec

// Attention use Radix decimal in MPASM options 
#define CLS 12
#define BS 8
#define TAB 9
#define CR 13
#define LF 10
#define Bell 7
#define ON 0	// logique inverse avec led tiree au +5V
#define OFF 1

#define Led_Rouge    PORTAbits.RA4
#define Allume 0
#define Eteint 1

#define MAX_LEN 80


unsigned int  i,j,k;
unsigned int dummy;
unsigned int j1;
unsigned int M;
unsigned int BRG_REG;
volatile int i1;
volatile char  c1;
volatile int count;
volatile unsigned int ErrComm;
long L;

char Texte[]="18F26K22 test RS232 C18\r\n 03/07/2012 rev a\n\r19200bds Quartz 10Mhz \r\n\0";
char *txt;
char buffer[MAX_LEN]="00000000000000000000000";	// buffer de reception
char received;

//--------- RS232 UART HARDWARE --------------

void Init_UART1(void);
int PutStr_RS(char *s);
void Put_RS(char * untel);
void CRLF();
void Tempo(long val);
void Octet2Hex(unsigned char number);
void Decompile_byte(Byte un);

void InterruptHandlerHigh (void);

void Decompile_byte(Byte un) {
Byte masque;
  masque = 0x80;
  while (masque > 0u )
 {
  if (un & masque)
      Put_RS(49u);  //  '1'
    else
      Put_RS(48u);  //  '0'

    masque =masque >>1;
     }
}

void Octet2Hex(unsigned char number)
{
char high,low;
  // high nibble
  high = ((number & 0xF0) >> 4) + 48; // + '0'
  if (high > '9')
    high =high + 7;
 // low nibble
  low = (number & 0x0F) + 48;          // +'0' low nibble
  if (low > '9')                       // '9'= 57u
    low += 7;                         // > '9'
  Put_RS(high);
  Put_RS(low);
  Put_RS('h');
 }


//gestionnaire d'interruption
//------------------------------
// High priority interrupt vector
#pragma code InterruptVectorHigh = 0x08
void InterruptVectorHigh (void)
{
  _asm
    goto InterruptHandlerHigh //jump to interrupt routine
  _endasm
}

// High priority interrupt routine
#pragma code
#pragma interrupt InterruptHandlerHigh
void InterruptHandlerHigh ()
{
  static char i ; // doit être statique pour conserver sa valeur entre les IT
  char C ;
//======== SERIAL======================

if(PIR1bits.RC1IF) // si une interruption UART1 arrive
  {
  c1 =Read1USART(); // le lire => RAZ  RCIF
  if(RCSTA1bits.FERR==1 )
   {
     RCSTA1bits.SPEN = 0 ;
     RCSTA1bits.SPEN= 1 ;
    c1 =Read1USART(); 
    ErrComm++;
      }
   if (RCSTA1bits.OERR==1)    // voir parag 16.1.26 p273
   {
       RCSTA1bits.CREN = 0 ;
       RCSTA1bits.CREN = 1 ;
       ErrComm++;
       c1 =Read1USART(); // le lire => RAZ  RCIF
     }
// if you want to echoed ,uncomment the 2 following lines
//    while(Busy1USART()); // par sécurité
//    if (PORTBbits.RB1==0) Write1USART(C); // echo
  
      if(C != CR && i<MAX_LEN)
      {
        buffer[i++]=C ; // stockage
        }else
        {
         buffer[i]='\0'; // fin de chaîne si CR
         i=0;
         received =1;
       } //if PIRbits.RCIF
     }
} // fin de routine interrupts


void Init_UART1(void)
{
// USART_BRGH_HIGH,32
// init 38400Bd a 20Mhz
// init 19200Bd a 10Mhz avec IT en rx
// voir para 18.5 spec sheet DS41159B page 186
Open1USART( USART_TX_INT_OFF &
USART_RX_INT_ON &
USART_ASYNCH_MODE &
USART_EIGHT_BIT &
USART_CONT_RX &
USART_BRGH_HIGH,32  
);
INTCONbits.PEIE = 0 ; // autorisation des IT des périphériques
INTCONbits.GIE = 0 ; // autorisation globale des IT
}

int PutStr_RS(char *s)
{
	int n;
	for (n = 0; *s; n++, s++)
	{
       	Put_RS(*s);
     	}
	return n;
}

void Put_RS(char * untel)
{
   	while(Busy1USART());
   	Write1USART(untel);
}

void CRLF()
{
  Put_RS(CR);  Put_RS(LF);
  }


void Tempo(long val)
{
while(val>0){val--;}
}

void main()
{
char a;
unsigned char d;

//OSCCON =0b01100000;
ANSELA=0;
TRISA = 0b00001111 ; 
TRISAbits.TRISA4 = 0;   // led rouge
LATA = 0x00;

ANSELC=0;
TRISCbits.TRISC6 = 0;
TRISCbits.TRISC7 = 1;
Led_Rouge=Allume;

Init_UART1();

Put_RS(CLS);   // clear  Vbray terminal Screen
Tempo(150000L);
Put_RS('*');
CRLF();
Put_RS('#');
CRLF();

// init pour interruptions ----
  INTCONbits.GIE = 1;    // active global interrupt
  INTCONbits.GIEL=1;
  RCSTA1bits.CREN= 1 ;
  PIE1bits.RC1IE = 1;
  INTCONbits.PEIE = 1;   // autorisation des IT des périphériques
 
ErrComm=0; 
buffer[0]=0;
received=0;
txt=&Texte[0];
k=PutStr_RS(txt);
CRLF();
Tempo(20000);
// write to the USART 
k=fprintf(_H_USART,"Init UART 19200bds Q=10Mhz\r\n"); 
k=fprintf(_H_USART,"hello\r\n");
k=fprintf(_H_USART,"Type some chars and CR to send them: ");
buffer[0]=0;
while(1)
{ 
 if (received==1) // test if reception occured
 {
  j=0;  
  Led_Rouge=Allume; 
 k= fprintf(_H_USART,"\r\nKeyboard entry : ");    
  while (buffer[j]!=0)   
  {
    a=buffer[j]; 
    Put_RS(a);
    j++;
  }
  received=0;
  buffer[0]=0;
 } 
Tempo(25000L); 
Led_Rouge=!Led_Rouge;
}
}
/* results on Vbray terminal
#
18F26K22 test RS232 C18
 03/07/2012 rev a
19200bds Quartz 10Mhz 

Init UART 19200bds Q=10Mhz
hello
Type some chars and CR to send them: 
Keyboard entry : 
Keyboard entry : hello chaps !
Keyboard entry : How are you today ?


*/
 

Even I am having the same problem I am using PIC18f4550 and programming it through C18 Compiler
I have got to know about the uart.h file but still I am confused that how to set

OpenUSART(config, spbrg);

Can any one illustrates me how to set the external crystal oscillator frequency like I am using 16Mhz Crystal oscillator
SO how to set this in the code

Even I've gone through the ""Configuration bit settings"" there are twelve mode for oscillator selection
like HS , EC mode
I have done that LED Blinking through the same iDE by selecting ""HS Oscillator"" in the configuration bits Setting

Please help me out in writing USART code
 

Status
Not open for further replies.

Similar threads

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top