Snippet:Serial port

From Curuxa

These snippets show how to program a microcontroller for being able to communicate with a computer through serial port using the CMSP-MAX Module.

The microcontroller must set the UART/USART/EUSART/AEUSART (depending on model) to asynchronous mode, specify the desired baud rate, etc (see the setup example).

For more information, read the setion Enhanced Universal Synchronous Asynchronous Receiver Transmitter (EUSART) module in the datasheet of the microcontroller you are using.

All these examples are designed for avoiding interrupts. This way is easier to program, but less efficient since the microcontroller stops waiting until the operation is finished.

Contents

Setup MBP40 at Fosc=8MHz

(for other Main Boards, check the datasheet)

// Setup UART to communicate through the serial port
void SetupSP() {
	//Baud rate timer: SPBRG=((Fosc/(16 * 9600) -1))
	//Baud rate = Fosc/(16*(SPBRG+1))
	//real resulting baud rate for Fosc=8MHz: 9615.384615 bauds
	// SPBRG=51, 
	SPBRGH=0;
	SPBRG=51;
	BRGH=1; //high speed
	CREN=1; //enable receiver
	TXEN=1; // (register TXSTA) enable transmitter
	SYNC=0; // (register TXSTA) asynchronous operation
	SPEN=1; // (register RCSTA) set TX/CK as output, RX/DT as input
	//...by default: 8 bits, no interrupts
}


Read a byte

Tested only on MBP40.

//Reads a byte from the serial port. If there is no data on the receiver buffer, wait indefinitely for the next incoming byte
unsigned int8 ReadSPWait(){
	unsigned int8 dummy;
	while(!RCIF) {
		if (OERR) {
			TXEN=0;
			TXEN=1;
			CREN=0;
			CREN=1;
		}
		if (FERR) {
			dummy=RCREG;
			TXEN=0;
			TXEN=1;
		}
	}
	return RCREG;
}
//Reads a byte from the serial port. If there is no data on the receiver buffer, return 0xFF
unsigned int8 ReadSP() {
	if(RCIF) return RCREG;
	else return 0xFF;
}


Write a bye

//Writes a byte to the serial port
void WriteSP(unsigned int8 value) {
	//wait for previous transmission to end
	while(!TXIF) {
		//do nothing
	}
	TXREG=value;
	Delay10us();
}


Real examples

You can find entire working sample programs as CMSP-MAX examples.


See also

  • CMSP-MAX, Module for serial port communications
  • PCBot a robot controlled from a PC, communications through serial port