C Programming Basics


Every C program has a function main()
The simplest C program is:

main()
{
}

Every statement ends with a semicolon

  x = a+b;


Comment starts with /*   ends with */

/* This is a comment */


Simple program -- increment Port A

#include "hc12.h"

main()
{
    DDRA  = 0xff;
    PORTA = 0;
    while(1)
    {
        PORTA = PORTA + 1;
        delay(100);
    }
}


Data Types:

   8-bit                    16-bit
---------------         -----------------
unsigned char             unsigned int
  signed char               signed int


Need to declare variable before using it:

signed char c;
unsigned int i;

Can initialize variable when you define it:

signed char c = 0xaa;
signed int i = 1000;


You tell compiler it you are using signed or unsiged numbers; 
the compiler will figure out whether to use BGT or BHI


Arrays:

unsigned char table[10];  /* Set aside 10 bytes for table */

Can refer to elements table[0] through table[9]

Can initialize and array:

table[] = {0xaa, 0x55, 0xa5, 0x5a};

Arithmetic operators:

 +  (add)           x = a+b;
 -  (subtract)      x = a-b;
 *  (multiply)      x = a*b;
 /  (divide)        x = a/b;
 %  (modulo)        x = a%b;

Logical operators

 &  (bitwise AND)               y = x & 0xaa;
 |  (bitwise OR)                y = x | 0xaa;
 ^  (bitwise XOR)               y = x ^ 0xaa;
 << (shift left)                y = x << 1;
 >> (shift right)               y = x >> 2;
 ~  (1's complement)            y = ~x;
 -  (2's complement - negate)   y = -x;


Check for equality - use ==

if (x == 5)

Check if two conditions true:

if ((x==5) && (y==10))


Check if either of two conditions true:

if ((x==5) || (y==10))

Assign a name to a number

 #define COUNT 5

 
Declare a function:  Tell what parameters it uses, what type 
of number it returns:

int read_port(int port);

If a function doesn't return a number, declare it to be type void

void delay(int 100);