8051 带奇偶校验 .c
时间: 2023-08-30 11:12:11 浏览: 75
以下是一个简单的8051程序,可以在TXD和RXD引脚上启用奇偶校验:
```c
#include <reg51.h>
void main() {
TMOD = 0x20; // 设置定时器1为8位自动重载模式
TH1 = 0xFD; // 设置波特率为9600
SCON = 0x50; // 设置为模式1,允许接收
PCON = 0x80; // 启用波特率倍增
ES = 1; // 允许串口中断
EA = 1; // 允许总中断
PS = 1; // 设置奇偶校验位
RI = 0; // 清除接收中断标志
TI = 0; // 清除发送中断标志
while (1); // 等待中断
}
void serial_ISR() interrupt 4 {
if (RI) { // 接收中断
RI = 0; // 清除接收中断标志
// 处理接收到的数据
}
if (TI) { // 发送中断
TI = 0; // 清除发送中断标志
// 处理发送完成
}
}
```
在PS寄存器中设置1可以启用奇偶校验位。如果要禁用奇偶校验,只需将PS寄存器设置为0即可。
在上面的程序中,serial_ISR()函数是一个中断服务程序,它会在接收到一个字节或发送完一个字节时被调用。在处理接收到的数据和发送完成之后,需要在serial_ISR()函数中清除RI和TI标志位。
相关问题
数组奇偶校验c语言代码
以下是一个用C语言实现数组奇偶校验的代码示例:
```c
#include <stdio.h>
// 奇偶校验函数
void parityCheck(int arr[], int size) {
int count = 0;
for (int i = 0; i < size; i++) {
// 统计数组中每个元素的二进制表示中1的个数
int num = arr[i];
while (num) {
count += num & 1;
num >>= 1;
}
}
// 判断奇偶性并输出结果
if (count % 2 == 0) {
printf("偶校验\n");
} else {
printf("奇校验\n");
}
}
int main() {
int arr[] = {1, 0, 1, 0, 1, 0, 1, 0}; // 示例数组
int size = sizeof(arr) / sizeof(arr[0]);
parityCheck(arr, size);
return 0;
}
```
这段代码实现了对数组进行奇偶校验。它通过统计数组中每个元素的二进制表示中1的个数,然后判断总数的奇偶性来确定校验结果。如果总数为偶数,则输出"偶校验";如果总数为奇数,则输出"奇校验"。
奇偶校验c语言实现
以下是奇偶校验的 C 语言实现:
```c
#include <stdio.h>
int main() {
int num, count = 0;
printf("Enter a number: ");
scanf("%d", &num);
// Counting number of 1s in binary representation of num
for(int i=0; i<sizeof(int)*8; i++) {
if(num & (1<<i))
count++;
}
// Checking parity
if(count % 2 == 0) {
printf("Parity bit should be 0.\n");
num <<= 1;
} else {
printf("Parity bit should be 1.\n");
num = (num << 1) | 1;
}
printf("Number with parity bit: %d\n", num);
return 0;
}
```
该程序首先从用户输入中获取一个整数。然后,它计算该数字的二进制表示中1的数量,以确定奇偶性。如果有偶数个1,则奇偶校验位应该是0,否则应该是1。然后程序将该奇偶校验位添加到原始数字中,并输出结果。
相关推荐
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)