MCS_51单片机汇编语言程序设计
数据排序
1,用c实现
#define Size 10
unsigned char Array[Size];
void main ()
{
bit Change;
unsigned char index;
unsigned char Temp;
do {
Change = 0;
for (index = 0; index < (Size-1); index++) {
if (Array[index] > Array[index+1]) {
Change = 1;
Temp = Array[index];
Array[index] = Array[index+1];
Array[index+1] = Temp;
}
}
} while (Change);
}
2,汇编实现、
Size equ 10 ; 数据个数
Array equ 50h ; 数据起始地址
Change equ 0 ; 交换标志
Sort:
mov r0, #Array
mov r7, #Size-1
clr Change
Goon:
mov a, @r0
mov r2, a
inc r0
mov B, @r0
cjne a, B, NotEqual
sjmp Next
NotEqual:
jc Next ; 前小后大, 不交换
setb Change ; 前大后小, 置交换标志
xch a, @r0 ; 交换
dec r0
xch a, @r0
inc r0
Next:
djnz r7, Goon
jb Change, Sort
ljmp $
end
2,程序跳转表
用c实现
void Func0() {}
void Func1() {}
void Func2() {}
void Func3() {}
void FuncEnter(unsigned char FuncID)
{
switch (FuncID) {
case 0: Func0(); break;
case 1: Func1(); break;
case 2: Func2(); break;
case 3: Func3(); break;
default: break;
}
}
void main()
{
FuncEnter(0);
FuncEnter(1);
FuncEnter(2);
FuncEnter(3);
while(1);
}
汇编实现:
org 0
ljmp Start
Func0: mov a, #0
ret
Func1: mov a, #1
ret
Func2: mov a, #2
ret
Func3: mov a, #3
ret
FuncEnter:
add a, acc ; ajmp 为二字节指令, 调用号 X 2
mov dptr, #FuncTab
jmp @a+dptr
FuncTab:
ajmp Func0
ajmp Func1
ajmp Func2
ajmp Func3
Start:
mov a, #0
call FuncEnter
mov a, #1
call FuncEnter
mov a, #2
call FuncEnter
mov a, #3
call FuncEnter
ljmp $
end
3,内存块移动
c语言实现
xdata unsigned char Buffer1[256] _at_ 0x3000;
xdata unsigned char Buffer2[256] _at_ 0x4000;
void main()
{
unsigned int index;
unsigned char xdata * ptr1;
unsigned char xdata * ptr2;
ptr1 = &Buffer1;
ptr2 = &Buffer2;
for (index=0; index <= 255; index++)
{
*ptr2++ = *ptr1++;
}
}
汇编语言实现
; 移动 3000H --> 4000H, 256 字节
mov r0, #30h
mov r1, #00h
mov r2, #40h
mov r3, #00h
mov r7, #0
Loop:
mov dph, r0
mov dpl, r1
movx a, @dptr
mov dph, r2
mov dpl, r3
movx @dptr, a
cjne r1, #0ffh, Goon1
inc r0
Goon1:
inc r1
cjne r3, #0ffh, Goon2
inc r2
Goon2:
inc r3
djnz r7, Loop
ljmp $
end
汇编
将 A 拆为二个 ASCII 码, 并存入 Result 开始的二个单元
Result equ 20h
org 0
ljmp Start
ASCIITab:
db '0123456789ABCDEF' ; 定义数字对应的ASCII表
BinToHex:
mov dptr, #ASCIITab
mov b, a ; 暂存 A
swap a
anl a, #0fh ; 取高四位
movc a, @a+dptr ; 查ASCII表
mov Result, a
mov a, b ; 恢复 A
anl a, #0fh ; 取低四位
movc a, @a+dptr ; 查ASCII表
mov Result+1, a
ret
Start:
mov sp, #40h
mov a, #1ah
call BinToHex
ljmp $
end
3存储器请零
/ 软件实验一 存储器块清零
xdata unsigned char Buffer[256] _at_ 0x4000;
void main()
{
unsigned int index;
unsigned char xdata * ptr;
ptr = &Buffer; // 起始地址
for (index = 0; index <= 255; index++) {
*ptr++ = 0; // 清0, 地址加一
}
}
汇编 实现
bcd码
将 Number 拆为三个 BCD 码, 并存入 Result 数组
void main()
{
unsigned char Result[3];
unsigned char Number;
Number = 123;
Result[0] = Number / 100; // 除以 100, 得百位数
Result[1] = (Number % 100) / 10; // 余数除以 10, 得十位数
Result[2] = Number % 10; // 余数为个位数
}
汇编