Documente Academic
Documente Profesional
Documente Cultură
University of Arkansas
ELEG3923 Microprocessor
Ch.7 Programming In C
Dr Jingxian Wu
Dr.
wuj@uark.edu
2
OUTLINE
DATA TYPE
• D t ttypes
Data
– unsigned char, signed char, unsigned int, signed int, sbit, bit and sfr
• unsigned char
– 8-bit.
8 bit. Most popular data type, matches most registers. Represent ASCII code or integers
in the range of 0 ~ 255.
– Example: write a C program to send the ASCII code of 0, 1, 2, A, B, C to port 1 (demo)
#include <reg51.h> // the definition of registers
void main (void)
{
unsigned char mynum[] = “012ABC”;
unsigned char z;
for (z = 0; z <=5; z++)
P1 = mynum[z];
y //port
p 1 is denoted as P1
}
– Example: write a C program to toggle all bits of P2 continuously
#include <reg51.h>
void main(void)
{
for ( ; ; ) // infinite loop
{
P1 = 0x55; // hex number: 0x55
P1 = 0xAA;
}
}
5
DATA TYPE
• signed
i d char
h
– an 8-bit number with the most significant bit representing sign (+ or -)
• Range: -128 ~ 127 (range of unsigned char: 0 ~ 255)
– Example: write a C program to send -33 to 3 to port 1
#include <reg51.h>
void main(void)
{
char mynum[] = {-3,-2,-1,0,1,2,3};
{-3 -2 -1 0 1 2 3}; // signed char
unsigned char z;
for (z = 0; z<=6; z++)
P1 = mynum[z];
}
• unsigned
i int
i
– 16-bit (needs to registers), range: 0 ~ 65535 (FFFFH)
– E.g.: unsigned int a;
• signed
i d iintt
– 16-bit, MSB represents sign. Range: -32768 ~ 32767
– E.g.: int a;
– Since int requires twice as many memory space as char,
char use unsigned or
signed int only when the number cannot be represented with unsigned or
signed char.
6
DATA TYPE
• sbit
bit
– Single bit, used to access single-bit addressable registers
– Example: write a C program to toggle bit D0 of P1 50,000 times
#include
#i l d <reg51.h>
51 h
sbit MYBIT = P1^0;
void main(void)
{
unsigned int z; ; 50000 times, cannot use char
for (z=0; z<=50000;z++)
{
MYBIT = 0;
MYBIT = 1;
}
}
• bit
– Used to access single bit of bit-addressable RAM (20H – 2FH)
– Example:
E ample: bit mybit
m bit = 0; // the compiler will
ill assign a RAM space to a
//automatically
• sfr
– Used to access special function registers
– example: sfr ACC = 0xE0; // the address of reg. A
7
OUTLINE
I/O PROGRAMMING
• B t size
Byte i I/O
– Example: write a program to get a byte of data from P0. If it’s less than 100,
send it to P1; otherwise send it to P2
• Self study:
S y examples
p 7-9,, 7-10
10
I/O PROGRAMMING
• Bit-addressable I/O Programming
– Example: write a program to monitor bit P1.5. If it is high, send 55H to P0;
otherwise send AAH to P2
11
LOGIC
• l i operators
logic t in
i C
– && (and), || (or), ! (not)
– Example: if (var1 < 3 && var2 == 1)
if (!(var > 5))
• Bit-wise logic operators
– Bit-by-bit logical operations: & (and), | (or), ^ (xor), ~ (not)
– Shifting: << (shift to left) >> (shift to right): NOT cyclic shift!
– Example
#include <reg51.h>
void main(void)
( )
{
P0=0x35 & 0x0F;
P1=0x04 | 0x68;
P2=0x04 ^ 0x78;
P3=~0x55;
P0 = 0x35 << 3;
}
13
OUTLINE
OUTLINE