Single-chip computer C language

Source: Internet
Author: User
Tags bitwise bitwise operators compact mixed

Single chip computer C language one ___________________________________________________________________

_____________________
Pretreatment
A macro definition:

1, without parameters:
#define-Identifier constant expression
/* #define是宏定义命令, Macro name (identifier) good habit to use the capital * *
#define NIL 0x80

2, with parameters:/* equivalent to small function * *
#define Macro Name (parameter table) string
/* Not only to line word string replacement also to be replaced by parameters, in the macro definition, the macro name and with the parentheses between the brackets should not add space, otherwise the space after the string as part of the replacement string, which is very error-prone
such as: #define SQ (A,B) a*b
Use: x=12;y=10;area=sq (x,y);/* area=12*10=120*/

The second document contains:

#include < filename > or #include "filename"
/* in C with a double reference form more insurance, in the C51 commonly used in the form of sharp brackets * *

Three "conditional compilation:
/* All program lines in a general source program participate in compiling, but sometimes you want to compile some of the content only under certain conditions, that is, to specify the conditions of compilation for a portion of the content. */

#if, #elif, #else, #endif, #ifdef, #ifndef
/* Select a different compilation scope, produce different code, provide versatility. */
* * If 8051 at 6MHZ and 12MHZ under
#ifdef cpu==8051
#define FREQ 6/* Program section * *
#else
#define FREQ 12/* Program section * *
#endif
* * So the following original program without any modification can be used for two kinds of clock frequency SCM System * *

Four others:
1, #error: To catch unpredictable compilation conditions
#if (myv!=0&&myv!=1)/* Assumes the value must be 0 or 1*/
#error MYV must be 1 or 0/* when error appears * *
#endif
2. #pragma: Used to transmit various compiler control commands to the compiler in the program
#pragma compile command sequence
* Example: To compile ex.c c51 ex.c debug Cod large as follows: * *
#pragma DB CD LA
#pragma disable
/* Prohibit interruption * *


Single-chip computer C language of the second _____________________________________________________________________________________
Type of data:
char int long
1:unsinged 0~255 0~65535 0~4294967295
2:signed-128~127-32768~32767-2147483648~2147483647

Pointer: * 3 bytes

Bit scalar: sbit
Special function Register: SFR
16-bit Special function register: Sfr16 occupies 2 memory units, 0~65535
Addressable bit: Sbit using the addressable bits in the internal ram of the 51 MCU and the addressable bits in the special function registers
SFR p0=0x80;
Sbit p0_1=p0^1;
/* Define the port address of the P0 port as 80H and define the P0.1 bit as p1_1*/

II. Data storage Type
Table 1. C51 Data storage Type
━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━
The correspondence relation between data storage type ┃ and storage space
━━━━━━━╋━━━━━━━━━━━━━━━━━━━━━━━━━━
Data┃ Direct addressing in-chip data storage area, fast speed of visit
Bdata┃ addressable data storage area, allowing bit-byte mixed access
Idata┃ indirect addressable data storage area, access to all RAM address space in the slice
Pdata┃ paging addressable data storage area (256 bytes) accessed by Movx @R0
Xdata┃ External Data Storage area (64K), accessed by Movx @DPTR
Code┃ Code Storage Area (64K), accessed by MOVC @DPTR
━━━━━━━┻━━━━━━━━━━━━━━━━━━━━━━━━━━
The storage type definition of the variable:
Char data var
/* character variable var is defined as the data storage type, and the C51 compiler will position the variable in the 51 SCM chip storage area.
Bit bdata flag
The/* bit variable flag is defined as the Bdata storage type, and the C51 compiler will position the variable in the bit addressing area in the storage area (RAM) of the data area in the 51 monolithic microcomputer: 20h--2fh*/


Three typedef: Redefining data types

TypeDef Existing data type new data type
typedef int word;
   /* defines word as Integer */
Word i,j;
    /* define I,J as int/*

Four bitwise operators:
━━━━┳━━━━━┳━━━━━┳━━━━━━┳━━━━━━┳━━━━━━
~┃&┃| ┃^┃<<┃>>
━━━━╋━━━━━╋━━━━━╋━━━━━━╋━━━━━━╋━━━━━━
Bitwise ┃ and ┃ bitwise-or ┃-bitwise OR ┃ left-shift ┃ right
━━━━┻━━━━━┻━━━━━┻━━━━━━┻━━━━━━┻━━━━━━

To shift: such as <<, a<<2, that is, to move binary a left two-bit, if a=0x8f, that is, 10001111,a=a<<2, will cause a=0x3c (00111100), the right complement 0.

V. Conditional operator:
Logical expression. Expression 1: Expression 2

Six pointers and address operators:
* Take content & Address

VII Coercion type conversion: (type) = Expression
(char *) 0xb000

sizeof the operator that takes the data type, the variable, and the byte number of the expression;

IX. continue: Interrupt statement: End of this cycle.


The three _____________________________________________________________________________________ of single-chip computer C language
Function:
Break service function and register group definition:

function type function name (form parameter table) [Interrupt n][using N]
N is an interrupt number, 0~31:
━━━━┳━━━━━┳━━━━━
Interrupt number ┃ interrupt vector ┃ entry address
━━━━╋━━━━━╋━━━━━
0┃ External Interrupt 0┃0003h
━━━━╋━━━━━╋━━━━━
1┃ Timer 0┃000BH
━━━━╋━━━━━╋━━━━━
2┃ External Interrupt 1┃0013h
━━━━╋━━━━━╋━━━━━
3┃ Timer 1┃001BH
━━━━╋━━━━━╋━━━━━
4┃ Serial Port ┃0023h
━━━━┻━━━━━┻━━━━━
The following n refers to one of the four working register groups: 0~3
The function target code is affected as follows:
Protects the current working register group to the stack at the entrance of the function; The specified work register contents are not changed, and the protected work Register group is recovered from the stack before the function returns.
Example (Timing 1ms):

#include <reg51.h>
Sbit p1_0=p1^0;

void Timer0 (void) Interrupt 1 using 1{
p1_0=! P1_0;
th0=-(1000/256);
tl0=-(1000%256);
}
Main () {
sp=0x60;
p1_0=0;
tmod=0x01;
th0=-(1000/256);
tl0=-(1000%256);
Ea=1;
Et0=1;
Tr0=1;
Do{}while (1);
}

/* Note:
1. If a floating-point operation is used in the interrupt function, the state of the floating-point register must be saved. (Save floating-point register functions as Pfsave in MATH.H, restore the state function of floating-point registers to Fprestore)
2. If other functions are called in the interrupt function, the Working register group used by the called function is consistent with the interrupt function.
*/


Single-chip computer C language four _____________________________________________________________________________________
One, local variables and global variables (external variables):

1, global variable if not at the beginning of the definition plus extern
2, the global variable will make the code long, occupy more memory

Second, storage mode:
Auto variable (AUTO): default, function call exists, exit disappears.

Internal variable static variable (static): static int a=5; is always present, exits do not disappear, but cannot be accessed.

Register variable (register): the fastest speed. Usually only gives the compiler a recommendation, by the compiler root
According to the actual situation determined. (see below)

Variable global variable (global):
External variables
static variable (static):

Register Variable Example:
#include <stdio.h>
Int_power (M,e)
int m;
Register int e;
{
Register int temp;
Temp=1;
for (; e;e--)
Temp*=m;
return (temp);
}
Main ()
{
......
}

Third, the function of the parameters and local variables of the memory mode:

Three kinds of memory modes: Small,compact,large.
The memory pattern of a function determines the function's parameters and the address space of the local variable in memory
Small: Internal RAM
Compact, large: external RAM
function type function name (form parameter table) [Memory mode]

Cases:
#pragma large/* default memory mode is large*/
extern int Calc (char i,int b) small; /* Specify small mode * *
extern int func (int i,float f) Large; /* Specify large mode * *
int large_te (int i,int k)//not specified, treated by default large mode/*
{
Return (Mtest (i,k) +2);
}

The use of memory mixed mode programming, make full use of limited storage space, also can accelerate the execution speed of the program.


Single-chip computer C language five _____________________________________________________________________________________
Array

1> Initialization array:
unsigned char a[5]={0x11,0x22,0x33,0x44,0x55}
Or
unsigned char a[] ={0x11,0x22,0x33,0x44,0x55,0x66}

3> array as a function parameter: Not only can the variable be used as the parameter of the function, but also the array name as the parameter of the function. An array name represents the first address of the array. When you use an array name as a parameter of a function, the parameter passes in the process of performing a function call using address passing. The first address of the actual parameter array is passed to the form parameter array in the modulated function, so that the two arrays occupy the same section of the deposit. See figure below:

A[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]

Starting address 1000

B[0] b[1] b[2] b[3] b[4] b[5] b[6] b[7] b[8] b[9]
Using the array name as the parameter of the function, you should define the array in both the keynote and the modulated function, not the array on one side. Also, the array types defined in the two functions must be identical, and if the type inconsistency will result in a compilation error. The length of the real parameter group and the type parameter group can be inconsistent, the compiler does not check the length of the parameter group, and simply passes the first address of the real parameter group to the row parameter group. If you want the row parameter group to get all the elements of the real argument group, you should make the length of the two arrays consistent. You can define a type parameter group without specifying a length, followed by a square bracket [] only after the array name. In order to handle the need for array elements in the modulated function, a separate parameter should be set to pass the number of array elements.
Example: Using an array as the parameter of a function to calculate the average of all elements in an array of two different lengths

#include <stdio.h>

Float average (array,n)
int n;
float array[];
{
int I;
float aver,sum=array[0];
for (i=1;i<n;i++)
Sum=sum+array[i];
aver=sum/n;
return (aver);
}
Main ()
{
Float pot_1[2]={99.9,88.8};
Float pot_2[3]={11,22,33.3};
Average (pot_1,2);
Average (pot_1,3);
}

Single-chip computer C language six _____________________________________________________________________________________
Software method to interfere with:
In engineering, we generally require a precision of 5% when collecting data, greater than this value will be considered invalid. I used 8535 to 32 data for collection (8535 with 10-bit AD, with watchdog), found that the data beat sometimes up to 7%, this is due to a variety of interference caused. Mainly from random interference, the following methods of interference to provide a simple way to remove:

1, White Noise: The most important statistical characteristics for the average value of 0, can take a few times to seek the average method of data collection;

2, Random interference: this point is significantly higher than or below the normal sampling value, so the median filter method, that is, the measured signal for the continuous sampling of M times, the size of the sorting, take the center of the size of the 1/3 sampling values for arithmetic average;

3, Power interference: the characteristics of a fixed period, it can be used to calculate the average time sampling method.
Because all sorts of sorting and average algorithm is easy to realize with C, so C is often used in the acquisition system software to interfere. As for the sorting algorithm can refer to the previous article, there is a classic program.
In practice, we use 9 values per road, sort, take the middle 3, and ask for an average. And then.. , the data per road is almost motionless.


Single-chip computer C language seven _____________________________________________________________________________________
Pointers: can operate directly on memory addresses
Based on the memory of the reference to the receptacle class as the parameter, it is not determined at compile time. Therefore, the method of selecting the memory for pointers can be omitted, with the length of these pointers being 1 bytes (idata *,data *,pdata *) or 2 (code *,xdata *).
Char XData *address;

The ADC0809 has 8 analog input channels, uses the interrupt mode, reads 8 channel's A/D conversion value in the interrupt function, stores separately in the external Ram 1000h~1007h unit. The ADC0809 port address is 00f0h.

The program defines two pointer variables * ADC and * Adcdata, pointing respectively to the ADC0809 port address (00f0h) and the external Ram cell address (1000h~1007h)
The channel number is fed by *adc=i, the ADC0809 is initiated for A/D conversion, and the INT1 interrupt occurs at the end of conversion. In the Interrupt service function int1 () through the TEMP=*ADC and *adcdata=temp, read A/D conversion results to the external RAM.

    #include <reg51.h>
    unsigned int xdata *adc;/* Define ADC0809 Port pointer */
& nbsp;   unsigned int xdata *adcdata; /* Define ADC0809 Data buffer pointers */
    unsigned char I;
Void Main ()
{
    adc=0x00f0; * Define port address and data buffer address */
    adcdata=0x1000;
    i=8/* ADC0809 has 8 analog input channels */
    ea=1; Ex1=1;it1=1; /* Open Interrupt/*
    *adc=i;/* Start adc0809*/
    while (I);/* Wait for 8 channels A/D conversion complete */
}
Void Int1 () Interrupt 2
{
    unsigned char tmp;
    TEMP=*ADC; * Read A/D conversion result */
&N bsp;   *adcdata=temp; /* Result values are stored in the data buffer */
    adcdata++;/* Data buffer address plus 1*/
    i-
    *ADC =i; /* Start next analog input channel A/D conversion */
}

In addition to using pointer variables to implement direct manipulation of memory addresses, the C51 compiler also provides a set of macros, the macro definition file is: "Absacc.h", which makes it easy to implement direct manipulation of any memory space, overwriting the above program:
#include <reg51.h>
#include <absacc.h> * * Contains the absolute address operation predefined header file * *
#define ADC 0x00f0; /* Define ADC0809 port Address * *
#define ADCDATA 0X1000/* Define Data buffer Address * *
unsigned char I;
void Main ()
{
i=8; /*adc0809 has 8 analog input channels * *
Ea=1;ex1=1;it1=1; /* Open Interrupt * *
Xbyte[adc]=i; /* Start 0809 * *
while (i); * * Wait 8 Channel conversion complete */
}

void Int1 () interrupt2 {
unsigned char tmp;
TMP=XBYTE[ADC]; /* Read A/D conversion result * *
i--;
xbyte[adcdata+i]=tmp; /** result values are stored in the data buffer * *
Xbyte[adc]=i; /* Start the next analog input channel A/d conversion * *
}

Subtract two pointers-----calculate the length of a string
#include <stdio.h>
Main () {
Char *s= "abcdef";
int strlen (char *s);
printf ("\ Length of '%%s ' =%%d\n", S,strlen (s));
}

int strlen (char *s) {
Char *p=s;
while (*p!= ' ") p++;
return (P-S);
}

The result: Length of ' abcdef ' =6

Note: The pointer is not allowed to add, multiply, divide, shift, or shielding operations, also does not allow the float type data and pointers to do addition, subtraction operation.

Abstract Type pointer:
The new ANSI standard adds a pointer type of "void *", an abstract pointer that defines a pointer variable but does not specify which type of data the pointer points to. Mandatory type conversions are required when assigning values:
Char *p1;
Void *P2;
p1= (char*) P2;
Abstract pointers can be used to access arbitrary absolute addresses within each storage area or to produce absolute calls

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.