noob questions about #defines and #undef

Go To Last Post
5 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hi all,

Currently I have a main.c, main.h, uart.c and uart.h and in my uart .h I define the baudrates for my uarts.

#define BAUDRATE1       19200//9600
#define BAUDRATE2       19200//9600

now in my uart init function (inside uart.c)I use that defined baudrate to initialize my uart. My question is, is it possible to have the BAUDRATE2 changed from a user entry in the main? My goal is to have user select whether they want to send a file or just run the program normally. When sending files, my baud rate has to be set to 9600 (because of the IC im using) and normal is 19200 (because of the rest of IC's).
Now if a user selects yes he wants to send a file, then I tried to #undef BAUDRATE2 and #define BAUDRATE2 = 9600 and then I recall uartinit, but when I print out BAUDRATE2, its still 19200. I think its because its defined in the uart.h and it will keep getting the values from there. I can't seem to come up with a way around it.

Any ideas?

Thanks in advance, I'll also post if I figure a way to achieve this.

Thank you,
noob

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I think the easiest way to toggle between 9600 ant 19200 Baud is to toggle the U2X bit in the usart control register. Set the UBRR value that you get 9600 Baud with U2X bit cleared, then set U2X to switch to 19200 Baud.

Regards
Sebastian

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

You do realize don't you that #define are just compile time constants and before the C compiler even gets to see the .c file any occurrence of BAUDRATE1 or BAURATE2 you have written will just have been string substituted with the characters "9600" or "19200"? You cannot #define or #undef at run time.

But what you are trying to achieve is possible:

#define UBRR_9600_VALUE F_CPU / 9600 / 16 - 1
#define UBRR_19200_VALUE F_CPU / 19200 / 16 - 1

int main(void) {
 UBRRL = UBRR_19200_VALUE;
 while(1) {
  wait_user_input();
  if (user_input = "send file") {
   UBRRL = UBRR_9600_VALUE;
   send_file();
   UBRRL = UBRR_19200_VALUE;
  }
 }
}

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

ohh I did not no that. I thought u could #undef at run time, and thank you, changing UBRRL worked!

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

This manual may be worth a squint:

http://gcc.gnu.org/onlinedocs/cpp/

While that's for the GCC version of CPP they should all behave pretty much the same.

Wikipedia have things in a slightly more digestible form:

http://en.wikipedia.org/wiki/C_p...