The following quick post gives an example of program made for the HP Prime that helps to compute Microchip baud rate generator values to use for initialization of the UART of the device.
If you've already work with Microchip microcontroller, you certainly had to compute at some point the value of the SPBRG register to have the UART works at your wanted baud rate. If so, you certainly remember the following table for the baud rate formula:
If you were like me, too lazy to compute yourself, you might instead have crossed your fingers and hope the frequency of your microcontroller and desired baud rate was a combinaison of their examples from their tables like this:
For myself, I now have a program in my HP Prime to help to compute this for me. Normally the two known things are:
- the frequency of the MCU
- the wanted baud rate
So basically the program will prompt user to enter these two values and then will compute for the possible asynchronous mode the value to use to have the PIC work at the wanted baud rate.
So here the code:
EvaluateThisMode(ParamFreq,ParamBaud,ParamTitle,ParamDivisor,ParamLimit,ParamAnswer)
BEGIN
LOCAL ExactBaud;
LOCAL SPBRG;
LOCAL PercentError;
PRINT(">>>>>> "+ParamTitle);
SPBRG:=Round(((ParamFreq/ParamBaud)/ParamDivisor)-1,0);
ExactBaud:=ParamFreq/(ParamDivisor*(SPBRG+1));
PercentError:=IP(((ExactBaud-ParamBaud)/ParamBaud)*10000)/100;
IF (SPBRG<ParamLimit) AND (ABS(PercentError)<2) THEN
PRINT(" "+ParamAnswer+"="+SPBRG+"("+SETBASE (SPBRG,4)+") - ERROR="+PercentError+"%");
ELSE
PRINT(" Not possible...");
SPBRG:=0;
END;
PRINT("");
RETURN SPBRG;
END;
EXPORT PicBaudHelper
BEGIN
LOCAL Freq;
LOCAL Baud;
INPUT({Freq,Baud},"Compute value for baud rate",{"Frequency","Baud"},{"Frequency in MHz","Wanted baud rate"},{8,9600},{8,9600});
Freq:=Freq*1000000;
PRINT;
PRINT("Frequency="+Freq+" - Baud rate="+Baud);
PRINT("");
EvaluateThisMode(Freq,Baud,"SYNC = 0, BRG16 = 0, BRGH = 0",64,256,"SPBRG:8");
EvaluateThisMode(Freq,Baud,"SYNC = 0, BRG16 = 0, BRGH = 1",16,256,"SPBRG:8");
EvaluateThisMode(Freq,Baud,"SYNC = 0, BRG16 = 1, BRGH = 0",16,65536,"SPBRG:16");
RETURN EvaluateThisMode(Freq,Baud,"SYNC = 0, BRG16 = 1, BRGH = 1",4,65536,"SPBRG:16");
END;
So let's suppose the clock frequency is 8 MHz and we want to work with 9600 bps, we will fill the blank as follows:
So from that example, we see they are four way to accomplish it and none is really better than the other since the result is still with a small error of 0.16% of the actual target baud rate. Personnally I like to work with 16-bits high baud rate so I would initialize my SPBRGH:16 to 207 or 0x00CF as written also inside parenthesis in hex.
If you have access to the Internet at the moment you need to compute this, you may also use this excellent online page: http://www.nicksoft.info/el/calc/?ac=spbrg
I wish you best, Dennis.
Aucun commentaire:
Enregistrer un commentaire