Continue to Site

Welcome to our site!

Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

  • Welcome to our site! Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

Code Styling Guide for embedded systems

Status
Not open for further replies.
Along the same lines of modular reusable code design, the one general comment that I would make is that when writing code, try to make it as general as possible. Think beyond the immediate project, and how you may need to use similar code in the future. A couple of minor allowances in your current code can make it much easier to reuse in the future.

The one mistake that I see most often is that inexperienced programmers love to hard code things (such as loop parameters) using literals, rather than using variables. It's usually because they are in a hurry, and want to get things running. A week later when they have to go back and change the code, it makes for lot of rewriting, and it costs them far more time than the little bit they save the first time around.
 
That is an interesting point. What is your opinion on using short macros to pass those variables to a subroutine? (assembly)

John
 
NEVER USE GOTO....
I have never liked using goto in C...
I did not even know there was a GOTO in C. I took my C/C++ class last year at the local JC and that was never covered. Guess it is not even worth teaching it...
 
I can't think of an occasion where I've needed goto in a c program. Can anyone think of code where using goto even makes sense?

Mike.
 
This is a topic I love. Somebody should write a good book about this. About style and structuring code. Especially about structuring code. Some organizations have strict guides that everybody must use inside the house.
This is good reading for example: **broken link removed**
And this.. **broken link removed**
and this: http://www.literateprogramming.com/indhill-cstyle.pdf
These links are perfect, exactly what I was looking for and I am sure they will benefit others as well. I really think well organized code helps others to help you when your stuck on a coding problem.
 
I can't think of an occasion where I've needed goto in a c program. Can anyone think of code where using goto even makes sense?

Mike.
Back in the 80's I use to write in Basic, and that was last time I ever saw the GOTO command. Sorta like:
if true
goto such and such
else some such...
 
That is an interesting point. What is your opinion on using short macros to pass those variables to a subroutine? (assembly)

John
I think there are a number of ways of making code more general. While I said to avoid the use of literals, you can still define your parameters at the top of your program with equ statements in assembly language, or constant statements in higher level languages. The compiler or assembler will still convert them to literals in the object code, but you now have the flexibility of changing things in one spot. As a simple example, suppose you have a serial I/O routine. You can define the number of data bits, stop bits and speed at the beginning of the program:
Code:
Databits equ 8
Stopbits equ 1
Baud equ 9600
Guess how many times I've tried to debug someone else's code where there was something like:
Code:
  movlw 8
  movwf ser_statReg
instead of
Code:
  movlw Databits
  movwf ser_statReg
And somewhere else there will be more hard coded parameters. Of course these all end up as literals in the object code, but if you have all of your parameters defined with equ's then you can go in later and easily change the number of data bits and/or stop bits without having to hunt though your code. But even more importantly, you can cut and paste your serial I/O routine from one project to another, and have a much easier time because your parameters are well defined.

I like to assign names to the individual bits in I/O ports so that if I end up having to reassign I/O points, I can often do this simply by changing the equ statements, and not have to change any other program code.

I do almost all of my microcontroller programming in assembly language. Given how time consuming it can be, I like to put that extra effort in to make sure that whatever I write, I'll be able to reuse it.
 
I can't think of an occasion where I've needed goto in a c program. Can anyone think of code where using goto even makes sense?

Someone thought me not to use "goto" when I was young, so I don't use it. I don't know whether it's good or bad, but there are some patterns where "goto" would be useful.

Code:
//list array elements separated by comma
int i;
char* a[n];

i = 0;
goto middle;
while (i++ < n) {
    printf("%s",",");
  middle:
    printf("%s",a[i]);
}

Code:
//escape from nested loops

while(something) {
  while(somethind_else) {
     for (i = 0; i < n; i++) {
        while(something_else_again) {
           if (error) goto done;
        }
     }
  }
}
done:

finalize();
 
If the language doesn't include 'exit' statements or 'continue' statements for getting out loops, then the goto may be the only practical alternative. But I think almost all languages have means for getting out of loops or jumping to the next iteration.
 
Jumping into and out of loops seems very dangerous. How are locals released, what happens to the stack, are labels defined in loops even visible from outside?
I'd prefer something like,
Code:
    continue=TRUE;
    while(something&&continue) {
     while(somethind_else&&continue) {
        for (i = 0; (i < n)&&continue; i++) {
            while(something_else_again&&continue) {
              if (error) continue=FALSE;
            }
        }
     }
    }
Still not very elegant but I think, a lot safer.

Mike.
 
OK ... C programers , while(! someflag) ; and someflag never changes , say waiting for a buffer full .. a single solution or more complex. Discuss please...

Edit Perhaps Pommie covered it ( missed the post ):oops:
 
OK ... C programers , while(! someflag) ; and someflag never changes , say waiting for a buffer full .. a single solution or more complex. Discuss please...

If you mean how to implement a timeout to prevent the program from getting stuck, a simple solution would be:
C:
uint16_t timeout = 1000; /* This gives 10 second timeout */
while((!flag) && timeout) {
    timeout--;    /* Decrement timeout by one */
    delay_ms(10); /* 10 ms delay */
}

I wouldn't write any more complex system than that unless I already have more complex tools available. For example a clock running in the background etc. Then you could do:
C:
uint32_t timeout;
timeout = clock_gettime();
while((!flag) && ((clock_gettime()-timeout) < 10)); /* 10 second timeout */
 
A pattern where go to would be useful? I haven't found a need. My version of your example is:
C:
//list array elements separated by
// comma
int i;
char* a[n];

i = -1;
while (i++ < (n-1));
    printf("%s",a[i]);
    printf("%f",",");
}
printf("%s",a[n]);

Instead of your example which was:
C:
//list array elements separated by comma
int i;
char* a[n];

i = 0;
goto middle;
while (i++ < n) {
    printf("%s",",");
  middle:
    printf("%s",a[i]);
}
 
Back when i took machines apart for a living ,sometimes the SW saved FE's an error tally... device,code count etc was very useful, I tried to do same in my amateurish way, with a PIC24 development board using the watchdog timer, eventually it sort of worked but didn't peruse it as reporting tallies is difficult using one, or even 4 leds...:) takes up IO as well... this is something of what I had...

Not all C code !
( ETO code tab not working ?)

#define _trapISR __attribute__((interrupt,no_auto_psv))

unsigned int WD_err __attribute__ ((persistent)) ;
unsigned int Err_dev __attribute__ ((persistent)) ;

Note.. This line sprinkled in main loop !

asm("CLRWDT"); // clear the 2 sec WDT

Note... one of the possible dead end routines

void HIH_read() // read humidity and temp sensor
{

WD_err=0x0028;
Err_dev=0x0027;
unsigned int raw_data= 0 ;
unsigned int HIH_data[4];
unsigned int x;
I2C_start_W(HIHaddr); // wake up HIH6030 HIHaddr 0x0027
I2C_endtx();
DLYm(50); // read delay
I2C_start_R(HIHaddr); // starts read HIH6030
for(x=0;x<3;x++)
…................
 
Jumping into and out of loops seems very dangerous. How are locals released, what happens to the stack, are labels defined in loops even visible from outside?
I'd prefer something like,
Code:
    continue=TRUE;
    while(something&&continue) {
     while(somethind_else&&continue) {
        for (i = 0; (i < n)&&continue; i++) {
            while(something_else_again&&continue) {
              if (error) continue=FALSE;
            }
        }
     }
    }
Still not very elegant but I think, a lot safer.

This is not going to work if there is some other code around inner loops. You would have to check the variable you called "continue" (which is BTW a reserved word) after termination of any loop which could've changed it.

C:
int done;

done = 0;
while(something) {
  while(somethind_else) {
     for (i = 0; i < n; i++) {
        while(something_else_again) {
           if (error) {
             done = 1;
              break;
           }
           // other code here
        }
        if (done) break;
        // other code here
     }
     if (done) break;
     // other code here
  }
  if (done) break;
  // other code here
}
 
A pattern where go to would be useful? I haven't found a need. My version of your example is:
C:
//list array elements separated by
// comma
int i;
char* a[n];

i = -1;
while (i++ < (n-1));
    printf("%s",a[i]);
    printf("%f",",");
}
printf("%s",a[n]);

Yes, and now if you want to change the code which prints the element, you need to do it twice.

I usually do something like

C:
//list array elements separated by comma
char* a[n];

for  (int i = 0; i < n; i++) {
    if (i) printf("%s",",");
    printf("%s",a[i]);
}

but clearly it is less efficient than the "goto" variant.
 
Status
Not open for further replies.

Latest threads

New Articles From Microcontroller Tips

Back
Top