當前位置:首頁 » 編程語言 » 單片機雙機通訊c語言
擴展閱讀
webinf下怎麼引入js 2023-08-31 21:54:13
堡壘機怎麼打開web 2023-08-31 21:54:11

單片機雙機通訊c語言

發布時間: 2022-07-19 05:18:13

㈠ 單片機雙機通信,兩個單片機的一方作為發送,另一方作為接收,分別調

#include<reg51.h>
#define uchar unsigned char
uchar distab[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e};
void delay(uchar a)
{
uchar i;
while(a--)for(i=0;i<120;i++);
}
main()
{
uchar i;
TMOD=0x20;
TH1=0xfd;
TL1=0xfd;
TR1=1;
SCON=0x40;
while(1)
{
for(i=0;i<16;i++)
{
SBUF=distab[i];
whileTI==0);
TI=0;
delay(200);
}
}
}
#include<reg51.h>
#define uchar unsigned char
main()
{
uchar i;
TMOD=0x20;
TH1=0xfd;
TL1=0xfd;
TR1=1;
SCON=0x50;
while(1)
{
if(RI)
{
RI=0;
P1=SBUF;
}
}
}

㈡ 單片機雙機通信以及單片機與pc機的通信

/*
說明:
1. U1為發信機,U2位收信機;
2. U1收到數據後會列印出AT89C51 U1-->..., 並循環點亮8個LED;
3. U2接收輸入數據後保存最新的30個字元,按『\』後輸出AT89C51 U2-->...
*/
#include <reg51.h> /* define 8051 registers */
#include <stdio.h> /* define I/O functions */

void delays(unsigned int ms)
{
unsigned int ii,jj;
for(ii=0;ii<ms;ii++)
for(jj=0;jj<5000;jj++);
}
void delayms(void)
{
unsigned int ii;
for(ii=0;ii<100;ii++);
}
void ledloop(unsigned char ss)
{
unsigned int ii;
P1=0xFF;
for(ii=0;ii<8;ii++)
{
P1=~(0x01<<ii);
delays(ss);
P1=0xff;
delays(ss);
}
P1=0xFF;
}

void initcom(void){
SCON = 0x52;
TMOD = 0x20;
TCON = 0x69;
TH1 = 0xf3;

}

void main (void){ /* main program */
unsigned char ch;
initcom();
//printf ("\n-----------------------");
//printf ("\n|Here is the receiver!|");
//printf ("\n-----------------------\n");
ledloop(10);

while (1){
P1=0;
delays(10);
P1=0xFF;
delays(10);
P1=0;
delays(10);
P1=0xFF;
delays(10);
ch = getchar();
if( (ch>30)&&(ch<123))
{
printf("\nAT89C51 U1-->%c\n", ch);
delayms();
ledloop(3);
}
}
}

㈢ 實現雙機通信的c語言代碼

代碼要求是什麼? 基本實現 ping 的功能?

ping 代碼

#include <windows.h>
#include <winsock2.h>

#define IP_RECORD_ROUTE 0x7

#define ICMP_ECHO 8
#define ICMP_ECHOREPLY 0
#define ICMP_MIN 8 // minimum 8 byte icmp packet (just header)

#define DEF_PACKET_SIZE 32 // Default packet size
#define MAX_PACKET 60000 // Max ICMP packet size 1024
#define MAX_IP_HDR_SIZE 60 // Max IP header size w/options

typedef struct _iphdr
{
unsigned int h_len:4; // Length of the header
unsigned int version:4; // Version of IP
unsigned char tos; // Type of service
unsigned short total_len; // Total length of the packet
unsigned short ident; // Unique identifier
unsigned short frag_and_flags; // Flags
unsigned char ttl; // Time to live
unsigned char proto; // Protocol (TCP, UDP etc)
unsigned short checksum; // IP checksum

unsigned int sourceIP;
unsigned int destIP;
} IpHeader;

//
// ICMP header structure
//
typedef struct _icmphdr
{
BYTE i_type;
BYTE i_code; // Type sub code
USHORT i_cksum;
USHORT i_id;
USHORT i_seq;
// This is not the standard header, but we reserve space for time
ULONG timestamp;
} IcmpHeader;

//
// IP option header - use with socket option IP_OPTIONS
//
typedef struct _ipoptionhdr
{
unsigned char code; // Option type
unsigned char len; // Length of option hdr
unsigned char ptr; // Offset into options
unsigned long addr[9]; // List of IP addrs
} IpOptionHeader;

//
// Function: FillICMPData
//
// Description:
// Helper function to fill in various fields for our ICMP request
//
void FillICMPData(char *icmp_data, int datasize)
{
IcmpHeader *icmp_hdr = NULL;
char *datapart = NULL;

icmp_hdr = (IcmpHeader*)(icmp_data); //+sizeof(IpHeader)
icmp_hdr->i_type = ICMP_ECHO; // Request an ICMP echo
icmp_hdr->i_code = 0;
icmp_hdr->i_id = (USHORT)GetCurrentProcessId();
icmp_hdr->i_cksum = 0;
icmp_hdr->i_seq = 0;

datapart = icmp_data + sizeof(IcmpHeader);
//
// Place some junk in the buffer
//
memset(datapart,'E', datasize - sizeof(IcmpHeader));
}
//---------------------------------------------------------------------------

USHORT checksum(USHORT *buffer, int size)
{
unsigned long cksum=0;

while (size > 1)
{
cksum += *buffer++;
size -= sizeof(USHORT);
}
if (size)
{
cksum += *(UCHAR*)buffer;
}
cksum = (cksum >> 16) + (cksum & 0xffff);
cksum += (cksum >>16);
return (USHORT)(~cksum);
}
//---------------------------------------------------------------------------

void DecodeIPOptions(char *buf, int bytes, void CALLBACK (*pDis)(const char* szMes))
{
IpOptionHeader *ipopt = NULL;
IN_ADDR inaddr;
int i;
HOSTENT *host = NULL;
char szMesBuffer[255];
ipopt = (IpOptionHeader *)(buf + 20);

if (pDis != NULL)
{
pDis("RR: ");
}
for(i = 0; i < (ipopt->ptr / 4) - 1; i++)
{
inaddr.S_un.S_addr = ipopt->addr[i];
if (i != 0)
{
if (pDis != NULL)
{
pDis(" ");
}
}
host = gethostbyaddr((char *)&inaddr.S_un.S_addr, sizeof(inaddr.S_un.S_addr), AF_INET);
if (host)
{
if (pDis != NULL)
{
wsprintf(szMesBuffer, "(%-15s) %s", inet_ntoa(inaddr), host->h_name);
pDis(szMesBuffer);
}
}
else
{
if (pDis != NULL)
{
wsprintf(szMesBuffer, "(%-15s)", inet_ntoa(inaddr));
pDis(szMesBuffer);
}
}
}
return;
}
//---------------------------------------------------------------------------

int DecodeICMPHeader(char *buf, int bytes, struct sockaddr_in *from, void CALLBACK (*pDis)(const char* szMes))
{
IpHeader *iphdr = NULL;
IcmpHeader *icmphdr = NULL;
unsigned short iphdrlen;
DWORD tick;
static int icmpcount = 0;
char szMesBuffer[255];
char szMesBuffer1[255];

iphdr = (IpHeader *)buf;
// Number of 32-bit words * 4 = bytes
iphdrlen = iphdr->h_len * 4;
tick = GetTickCount();

if ((iphdrlen == MAX_IP_HDR_SIZE) && (!icmpcount))
DecodeIPOptions(buf, bytes, pDis);

if (bytes < iphdrlen + ICMP_MIN)
{
//printf("Too few bytes from %s\n", inet_ntoa(from->sin_addr));
if (pDis != NULL)
{
wsprintf(szMesBuffer, "Too few bytes from %s", inet_ntoa(from->sin_addr));
pDis(szMesBuffer);
}
}
icmphdr = (IcmpHeader*)(buf + iphdrlen);

if (icmphdr->i_type != ICMP_ECHOREPLY)
{
//printf("nonecho type %d recvd\n", icmphdr->i_type);
if (pDis != NULL)
{
wsprintf(szMesBuffer, "nonecho type %d recvd", icmphdr->i_type);
pDis(szMesBuffer);
}
return -1;
}
// Make sure this is an ICMP reply to something we sent!
//
if (icmphdr->i_id != (USHORT)GetCurrentProcessId())
{
//printf("someone else's packet!\n");
if (pDis != NULL)
{
pDis("someone else's packet!");
}
return -1;
}
//printf("%d bytes from %s:", bytes, inet_ntoa(from->sin_addr));
//printf(" icmp_seq = %d. ", icmphdr->i_seq);
//printf(" time: %d ms", tick - icmphdr->timestamp);
//printf("\n");
if (pDis != NULL)
{
wsprintf(szMesBuffer, "%d bytes from %s:", bytes, inet_ntoa(from->sin_addr));
wsprintf(szMesBuffer1, " icmp_seq = %d. ", icmphdr->i_seq);
lstrcat(szMesBuffer, szMesBuffer1);
wsprintf(szMesBuffer1, " time: %d ms", tick - icmphdr->timestamp);
lstrcat(szMesBuffer, szMesBuffer1);
wsprintf(szMesBuffer1, " TTL = %d", iphdr->ttl);
lstrcat(szMesBuffer, szMesBuffer1);
pDis(szMesBuffer);
}

icmpcount++;
return tick - icmphdr->timestamp;
}
//---------------------------------------------------------------------------

ping(const char* szTargetAddress, int iDataSize, int iTimeOut, int iTimes, bool bReply, void CALLBACK (*pDis)(const char* szMes))
{
WSADATA wsaData;
SOCKET sockRaw = INVALID_SOCKET;
struct sockaddr_in dest,
from;
int bread,
fromlen = sizeof(from),
timeout = iTimeOut,
ret;
char *icmp_data = NULL,
*recvbuf = NULL;
unsigned int addr = 0;
USHORT seq_no = 0;
struct hostent *hp = NULL;
IpHeader ip_header;
IpOptionHeader ipopt;
char szMesBuffer[255];

if (timeout > 3000)
timeout = 3000;
else if (timeout < 100)
timeout = 100;

if (pDis != NULL)
{
wsprintf(szMesBuffer, "ping %s with %d bytes of data:", szTargetAddress, iDataSize);
pDis(szMesBuffer);
}

if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
//printf("WSAStartup() failed: %d\n", GetLastError());
if (pDis != NULL)
{
wsprintf(szMesBuffer, "WSAStartup() failed: %d", GetLastError());
pDis(szMesBuffer);
}
return -1;
}

sockRaw = WSASocket(AF_INET, SOCK_RAW, IPPROTO_ICMP, NULL, 0, WSA_FLAG_OVERLAPPED);
if (sockRaw == INVALID_SOCKET)
{
//printf("WSASocket() failed: %d\n", WSAGetLastError());
if (pDis != NULL)
{
wsprintf(szMesBuffer, "WSASocket() failed: %d", WSAGetLastError());
pDis(szMesBuffer);
}
return -1;
}

// Set the send/recv timeout values
//
bread = setsockopt(sockRaw, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout));
if(bread == SOCKET_ERROR)
{
//printf("setsockopt(SO_RCVTIMEO) failed: %d\n", WSAGetLastError());
if (pDis != NULL)
{
wsprintf(szMesBuffer, "setsockopt(SO_RCVTIMEO) failed: %d", WSAGetLastError());
pDis(szMesBuffer);
}
return -1;
}
bread = setsockopt(sockRaw, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout));
if (bread == SOCKET_ERROR)
{
//printf("setsockopt(SO_SNDTIMEO) failed: %d\n", WSAGetLastError());
if (pDis != NULL)
{
wsprintf(szMesBuffer, "setsockopt(SO_SNDTIMEO) failed: %d", WSAGetLastError());
pDis(szMesBuffer);
}
return -1;
}
memset(&dest, 0, sizeof(dest));
//
// Resolve the endpoint's name if necessary
//
dest.sin_family = AF_INET;
if ((dest.sin_addr.s_addr = inet_addr(szTargetAddress)) == INADDR_NONE)
{
if ((hp = gethostbyname(szTargetAddress)) != NULL)
{
memcpy(&(dest.sin_addr), hp->h_addr, hp->h_length);
dest.sin_family = hp->h_addrtype;
//printf("dest.sin_addr = %s\n", inet_ntoa(dest.sin_addr));
if (pDis != NULL)
{
wsprintf(szMesBuffer, "dest.sin_addr = %s", inet_ntoa(dest.sin_addr));
pDis(szMesBuffer);
}
}
else
{
//printf("gethostbyname() failed: %d\n", WSAGetLastError());
if (pDis != NULL)
{
wsprintf(szMesBuffer, "gethostbyname() failed: %d", WSAGetLastError());
pDis(szMesBuffer);
}
return -1;
}
}
//
// Create the ICMP packet
//

int datasize = iDataSize;
if (datasize < 0)
datasize = DEF_PACKET_SIZE;

datasize += sizeof(IcmpHeader);

if (datasize > MAX_PACKET)
datasize = MAX_PACKET;

icmp_data = (char *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, MAX_PACKET);
recvbuf = (char *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, MAX_PACKET);
if (!icmp_data)
{
//printf("HeapAlloc() failed: %d\n", GetLastError());
if (pDis != NULL)
{
wsprintf(szMesBuffer, "HeapAlloc() failed: %d", GetLastError());
pDis(szMesBuffer);
}
return -1;
}
//memset(icmp_data, 0, datasize); //, MAX_PACKET
FillICMPData(icmp_data, datasize);
//
// Start sending/receiving ICMP packets
//
int nCount = 0;
int iReceiveCount = 0;
if (iTimes < 2)
{
iTimes = 2;
}
while(1)
{
int bwrote;

if (nCount++ == iTimes)
break;

((IcmpHeader*)icmp_data)->i_cksum = 0;
((IcmpHeader*)icmp_data)->timestamp = GetTickCount();
((IcmpHeader*)icmp_data)->i_seq = seq_no++;
((IcmpHeader*)icmp_data)->i_cksum = checksum((USHORT*)icmp_data, datasize);

bwrote = sendto(sockRaw, icmp_data, datasize, 0, (struct sockaddr*)&dest, sizeof(dest));
if (bwrote == SOCKET_ERROR)
{
if (WSAGetLastError() == WSAETIMEDOUT)
{
//printf("timed out\n");
if (pDis != NULL)
{
wsprintf(szMesBuffer, "timed out");
pDis(szMesBuffer);
}
continue;
}
//printf("sendto() failed: %d\n", WSAGetLastError());
if (pDis != NULL)
{
wsprintf(szMesBuffer, "sendto() failed: %d", WSAGetLastError());
pDis(szMesBuffer);
}
return -1;
}
if (bwrote < datasize)
{
//printf("Wrote %d bytes\n", bwrote);
if (pDis != NULL)
{
wsprintf(szMesBuffer, "Wrote %d bytes", bwrote);
pDis(szMesBuffer);
}
}
bread = recvfrom(sockRaw, recvbuf, MAX_PACKET, 0, (struct sockaddr*)&from, &fromlen);
if (bread == SOCKET_ERROR)
{
if (WSAGetLastError() == WSAETIMEDOUT)
{
//printf("timed out\n");
if (pDis != NULL)
{
wsprintf(szMesBuffer, "timed out");
pDis(szMesBuffer);
}
continue;
}
//printf("recvfrom() failed: %d\n", WSAGetLastError());
if (pDis != NULL)
{
wsprintf(szMesBuffer, "recvfrom() failed: %d", WSAGetLastError());
pDis(szMesBuffer);
}
return -1;
}
DecodeICMPHeader(recvbuf, bread, &from, pDis); //return replay time ms
iReceiveCount++;

Sleep(50);//1000
}
// Cleanup
//
if (sockRaw != INVALID_SOCKET)
closesocket(sockRaw);
HeapFree(GetProcessHeap(), 0, recvbuf);
HeapFree(GetProcessHeap(), 0, icmp_data);

WSACleanup();
if (pDis != NULL && bReply)
{
pDis(" ");
nCount--;
wsprintf(szMesBuffer, "Packets: Sent = %d, Received = %d, Lost = %d (%d%s", nCount, iReceiveCount, nCount - iReceiveCount, (nCount - iReceiveCount) * 100 / nCount, "% loss)");
pDis(szMesBuffer);
pDis(" ");
}

return 0;
}
//---------------------------------------------------------------------------

調用方法:

ping(
szTargetAddress, //目標地址 //IP 或網址
iDataSize, //數據包大小
iTimeOut, //延時
iTimes, //發送次數
bReply, //是否顯示信息
CALLBACK (*pDis)(const char* szMes)//顯示信息的函數指針
);

void pingMessage(const char* szMes);

main()
{
ping("127.0.0.1", 32, 500, 5, true, pingMessage);
}

void pingMessage(const char* szMes)
{
printf("%s\n", szMes);
}

㈣ 求一個51 雙機通信 的程序 C語言編寫 內容 單片機A傳送數字0~255

顯示不正常可能是你編碼的問題,傳輸數據兩邊一定要協調一致,比如都是char型,或者int型,然後接收到之後對應的處理顯示,慢慢調試一下就好了

㈤ 51單片機c語言串列雙機通信的問題。請直接給我程序,要有注釋說明。

先設計出來電路,然後再談編程的問題。

㈥ 單片機雙機通信程序

雙機通信不需要安裝虛擬埠軟體 ,兩機通過TXD <==> RXD 直接通信。
#include<reg51.h>
#define uchar unsigned char;
#define uint unsigneed int;
uchar a0,a1,a2,a3,temp,i;
uchar code tab[ ]={0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x6F};

sbit P2_0=P2^0;
sbit P2_1=P2^1;
sbit P2_2=P2^2;
sbit P2_3=P2^3;

void delay(int ms)
{
while(ms--)
for(i=0;i<123;i++);
}

void initUART()
{
TMOD=0x20; //M1=1,M0=0 定時器1工作方式2(定時常數重裝,8 位)
SCON=0x50; //SM0=0,SM1=1,REN=1 串口工作方式1,允許接收
TH1=0xfd; //晶振11.0592時,波特率9600
TL1=TH1; //TL1計數,溢出後,TH1值送入TL1
EA=1; //開總中斷
ES=1; //允許串口中斷
TR1=1; //啟動定時器1
}

void disp()
{
a0=temp%2;
a1=temp/2%2;
a2=temp/2/2%2;
a3=temp/2/2/2%2;

P2_0=0;
P0=tab[a0];
delay(1);
P2_0=1;
P2_1=0;
P0=tab[a1];
delay(1);
P2_1=1;
P2_2=0;
P0=tab[a2];
delay(1);
P2_2=1;
P2_3=0;
P0=tab[a3];
delay(1);
P2_3=1;
}
void main()
{
initUART(); //調用串口初始化子程序
while(1)
{
disp();
SBUF=P1;
while(TI==0);
TI=0;
}
}

void UARTinterrupt( ) interrupt 4
{
if(RI)
{
RI=0;
temp=SBUF;
}
}

㈦ 單片機雙機通信系統設計

//兩個51單片機,兩機的串口交叉連線,雙機互發數據
//接收方採用兩位數顯示收到的數據
//下列雙機通信程序,適用於雙方同時使用
//經過編譯、模擬成功
//顯示函數應該根據自己的設備進行改寫
//===============================
#include<reg52.h>
#define uchar unsigned char
#define uint unsigned int
uchar Rbuf = 0;
uchar code dis_7[] = {0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f, 0x77, 0x7c, 0x39, 0x5e, 0x79, 0x71, 0x00};//共陰段碼
//段碼表 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F, off
//-------------------------------
void delay(uint k)
{
uint i, j;
for(i = 0; i < k; i++) for(j = 0; j < 200; j++);
}
//-------------------------------
void Display(uchar x)
{
P0 = dis_7[x / 16]; //輸出高四位
P2 = 0xFE;
delay(2);
P0 = dis_7[x % 16]; //輸出低四位
P2 = 0xFD;
delay(2);
}
//-------------------------------
void UART()interrupt 4
{
if(RI) {
RI = 0; //清除中斷標志
Rbuf = SBUF;
}
if(TI) {
TI = 0; //清除中斷標志
}
}
//-------------------------------
void main() //主函數
{
uchar t1, i;
SCON = 0x50; //串口工作在方式1
PCON &= 0x7F; //SMOD=0
TMOD = 0x20; //定時器1當做波特率發生器
TH1 = 0xFD; //初值, 9600 @ 11.0592MHz
TL1 = 0xFD;
TR1 = 1;
while (1){
for (i = 0; i < 250; i++) Display(Rbuf);
SBUF = t1; //發送數據
t1++;
}
}
//===============================

㈧ 求51單片機通過I/O口模擬spi實現雙機通信的c語言代碼

#include <reg52.h>
#include <intrins.h>
#define MODE 0 //MODE=1時 為發送代碼 MODE=0時 為接收代碼
typedef unsigned char uchar;
//****************************************IO埠定義***************************************
sbit MISO =P1^2;
sbit MOSI =P1^3;
sbit SCK =P1^1;
sbit CE =P1^0;
sbit CSN =P3^2;
sbit IRQ =P3^3;
//******************************************************************************************
uchar bdata sta; //狀態標志
sbit RX_DR =sta^6;
sbit TX_DS =sta^5;
sbit MAX_RT =sta^4;
//*********************************************NRF24L01*************************************
#define TX_ADR_WIDTH 5 // 5 uints TX address width
#define RX_ADR_WIDTH 5 // 5 uints RX address width
#define TX_PLOAD_WIDTH 32 // 32 uints TX payload
#define RX_PLOAD_WIDTH 32 // 32 uints TX payload
uchar const TX_ADDRESS[TX_ADR_WIDTH]= {0x34,0x43,0x10,0x10,0x01}; //本地地址
uchar const RX_ADDRESS[RX_ADR_WIDTH]= {0x34,0x43,0x10,0x10,0x01}; //接收地址
uchar code Tx_Buf[TX_PLOAD_WIDTH]={0xff,0xee,0x11,0x22,0x33,0xaa,0xbb,0x11,0x22,0x33,0xaa,0xbb,0x11,0x22,
0x33,0xaa,0xbb,0x11,0x22,0x33,0xaa,0xbb,0x11,0x22,0x33,0xaa,0xbb,0x11,0x22,0x33,0xee,0xff};//發送數據
uchar Rx_Buf[RX_PLOAD_WIDTH];//接收數據
//***************************************NRF24L01寄存器指令*******************************************************
#define READ_REG 0x00 // 讀寄存器指令
#define WRITE_REG 0x20 // 寫寄存器指令
#define RD_RX_PLOAD 0x61 // 讀取接收數據指令
#define WR_TX_PLOAD 0xA0 // 寫待發數據指令
#define FLUSH_TX 0xE1 // 沖洗發送 FIFO指令
#define FLUSH_RX 0xE2 // 沖洗接收 FIFO指令
#define REUSE_TX_PL 0xE3 // 定義重復裝載數據指令
#define NOP 0xFF // 保留
//*************************************SPI(nRF24L01)寄存器地址****************************************************
#define CONFIG 0x00 // 配置收發狀態,CRC校驗模式以及收發狀態響應方式
#define EN_AA 0x01 // 自動應答功能設置
#define EN_RXADDR 0x02 // 可用信道設置
#define SETUP_AW 0x03 // 收發地址寬度設置
#define SETUP_RETR 0x04 // 自動重發功能設置
#define RF_CH 0x05 // 工作頻率設置
#define RF_SETUP 0x06 // 發射速率、功耗功能設置
#define STATUS 0x07 // 狀態寄存器
#define OBSERVE_TX 0x08 // 發送監測功能
#define CD 0x09 // 地址檢測
#define RX_ADDR_P0 0x0A // 頻道0接收數據地址
#define RX_ADDR_P1 0x0B // 頻道1接收數據地址
#define RX_ADDR_P2 0x0C // 頻道2接收數據地址
#define RX_ADDR_P3 0x0D // 頻道3接收數據地址
#define RX_ADDR_P4 0x0E // 頻道4接收數據地址
#define RX_ADDR_P5 0x0F // 頻道5接收數據地址
#define TX_ADDR 0x10 // 發送地址寄存器
#define RX_PW_P0 0x11 // 接收頻道0接收數據長度(1到32位元組)
#define RX_PW_P1 0x12 // 接收頻道1接收數據長度
#define RX_PW_P2 0x13 // 接收頻道2接收數據長度
#define RX_PW_P3 0x14 // 接收頻道3接收數據長度
#define RX_PW_P4 0x15 // 接收頻道4接收數據長度
#define RX_PW_P5 0x16 // 接收頻道5接收數據長度
#define FIFO_STATUS 0x17 // FIFO棧入棧出狀態寄存器設置
/******************************************延時函數********************************************************/
//長延時
void Delay(unsigned int s)
{
unsigned int i,j;
for(i=0;i<1000;i++)for(j=0;j<s;j++);
}
//短延時
void delay_ms(unsigned int x)
{
unsigned int i,j;
i=0;
for(i=0;i<x;i++)
{
j=108;;
while(j--);
}
}
/************************************IO 口模擬SPI匯流排 代碼************************************************/
uchar SPI_RW(uchar byte)
{
uchar bit_ctr;
for(bit_ctr=0;bit_ctr<8;bit_ctr++)
{
MOSI=(byte&0x80);

byte=(byte<<1);
SCK=1;
byte|=MISO;
//led=MISO;Delay(150);
SCK=0;
}
return(byte);
}
uchar SPI_RW_Reg (uchar reg,uchar value) // 向寄存器REG寫一個位元組,同時返回狀態位元組
{
uchar status;
CSN=0;
status=SPI_RW(reg);
SPI_RW(value);
CSN=1;
return(status);
}
uchar SPI_Read (uchar reg )
{
uchar reg_val;
CSN=0;
SPI_RW(reg);
reg_val=SPI_RW(0);
CSN=1;
return(reg_val);
}
uchar SPI_Write_Buf(uchar reg, uchar *pBuf, uchar bytes)
{
uchar status,byte_ctr;
CSN = 0; // Set CSN low, init SPI tranaction
status = SPI_RW(reg); // Select register to write to and read status byte
for(byte_ctr=0; byte_ctr<bytes; byte_ctr++) // then write all byte in buffer(*pBuf)
SPI_RW(*pBuf++);
CSN = 1; // Set CSN high again
return(status); // return nRF24L01 status byte
}
#if MODE
/*******************************發*****送*****模*****式*****代*****碼*************************************/
void TX_Mode(void)
{
CE=0;

SPI_RW_Reg(FLUSH_TX,0x00);
SPI_Write_Buf(WRITE_REG + TX_ADDR, TX_ADDRESS, TX_ADR_WIDTH); // Writes TX_Address to nRF24L01
SPI_Write_Buf(WRITE_REG + RX_ADDR_P0, TX_ADDRESS, TX_ADR_WIDTH); // RX_Addr0 same as TX_Adr for Auto.Ack
SPI_RW_Reg(WRITE_REG + EN_AA, 0x01); // Enable Auto.Ack:Pipe0
SPI_RW_Reg(WRITE_REG + EN_RXADDR, 0x01); // Enable Pipe0
SPI_RW_Reg(WRITE_REG + SETUP_RETR, 0x1a); // 500us + 86us, 10 retrans...1a
SPI_RW_Reg(WRITE_REG + RF_CH, 40); // Select RF channel 40
SPI_RW_Reg(WRITE_REG + RF_SETUP, 0x07); // TX_PWR:0dBm, Datarate:1Mbps, LNA:HCURR
SPI_RW_Reg(WRITE_REG + RX_PW_P0, RX_PLOAD_WIDTH); //設置接收數據長度,本次設置為2位元組
SPI_RW_Reg(WRITE_REG + CONFIG, 0x0e);
CE=1;
delay_ms(100);
}
void Transmit(unsigned char * tx_buf)
{
CE=0; //StandBy I模式
SPI_Write_Buf(WRITE_REG + RX_ADDR_P0, TX_ADDRESS, TX_ADR_WIDTH); // 裝載接收端地址
SPI_RW_Reg(FLUSH_TX,0x00);
SPI_Write_Buf(WR_TX_PLOAD, tx_buf, TX_PLOAD_WIDTH); // 裝載數據
SPI_RW_Reg(WRITE_REG + CONFIG, 0x0e); // IRQ收發完成中斷響應,16位CRC,主發送
CE=1; //置高CE,激發數據發送
delay_ms(150);
}
#else
/*******************************接*****收*****模*****式*****代*****碼*************************************/
uchar SPI_Read_Buf(uchar reg, uchar *pBuf, uchar uchars)
{
uchar status,uchar_ctr;

CSN = 0; // Set CSN low, init SPI tranaction
status = SPI_RW(reg); // Select register to write to and read status uchar

for(uchar_ctr=0;uchar_ctr<uchars;uchar_ctr++)
pBuf[uchar_ctr] = SPI_RW(0); //

CSN = 1;
return(status); // return nRF24L01 status uchar
}
/******************************************************************************************************/
/*函數:unsigned char nRF24L01_RxPacket(unsigned char* rx_buf)
/*功能:數據讀取後放如rx_buf接收緩沖區中
/******************************************************************************************************/
unsigned char nRF24L01_RxPacket(unsigned char* rx_buf)
{
unsigned char revale=0;
sta=SPI_Read(STATUS); // 讀取狀態寄存其來判斷數據接收狀況
if(RX_DR) // 判斷是否接收到數據
{
//CE = 0; //SPI使能
SPI_Read_Buf(RD_RX_PLOAD,rx_buf,RX_PLOAD_WIDTH);// read receive payload from RX_FIFO buffer
revale =1; //讀取數據完成標志
//Delay(100);
}
SPI_RW_Reg(WRITE_REG+STATUS,sta); //接收到數據後RX_DR,TX_DS,MAX_PT都置高為1,通過寫1來清楚中斷標志
return revale;
}
/****************************************************************************************************/
/*函數:void RX_Mode(void)
/*功能:數據接收配置
/****************************************************************************************************/
void RX_Mode(void)
{
CE=0;

SPI_RW_Reg(FLUSH_RX,0x00);
//SPI_Write_Buf(WRITE_REG + TX_ADDR, TX_ADDRESS, TX_ADR_WIDTH); // Writes TX_Address to nRF24L01
SPI_Write_Buf(WRITE_REG + RX_ADDR_P0, TX_ADDRESS, TX_ADR_WIDTH); // RX_Addr0 same as TX_Adr for Auto.Ack

SPI_RW_Reg(WRITE_REG + EN_AA, 0x01); // Enable Auto.Ack:Pipe0
SPI_RW_Reg(WRITE_REG + EN_RXADDR, 0x01); // Enable Pipe0
//SPI_RW_Reg(WRITE_REG + SETUP_RETR, 0x1a); // 500us + 86us, 10 retrans...1a
SPI_RW_Reg(WRITE_REG + RF_CH, 40); // Select RF channel 40
SPI_RW_Reg(WRITE_REG + RX_PW_P0, RX_PLOAD_WIDTH); //設置接收數據長度,本次設置為2位元組
SPI_RW_Reg(WRITE_REG + RF_SETUP, 0x07); // TX_PWR:0dBm, Datarate:1Mbps, LNA:HCURR
SPI_RW_Reg(WRITE_REG + CONFIG, 0x0F);
CE=1;
delay_ms(130);
}
//************************************串口初始化*********************************************************
void StartUART( void )
{ //波特率9600
SCON = 0x50;
TMOD = 0x20;
TH1 = 0xFD;
TL1 = 0xFD;
PCON = 0x00;
TR1 = 1;
}
//************************************通過串口將接收到數據發送給PC端**************************************
void R_S_Byte(uchar R_Byte)
{
SBUF = R_Byte;
while( TI == 0 ); //查詢法
TI = 0;
}
#endif
//************************************主函數************************************************************
void main()
{
int i=0;
CE=0;
SCK=0;
CSN=1;
P1=0x00;
#if MODE //發送 模式代碼
TX_Mode();
//SPI_RW_Reg(FLUSH_RX,0x00);
while(1)
{
Transmit(Tx_Buf);
Delay(10);
sta=SPI_Read(READ_REG + STATUS);
if(TX_DS)
{
P1=sta; //8位LED顯示當前STATUS狀態 發送中斷應使bit5 = 1 燈滅
Delay(100);
SPI_RW_Reg(WRITE_REG + STATUS,sta);
}
if(MAX_RT) //如果是發送超時
{
P1=0x0f; //發送超時時 8位LED燈 bit4 = 1 燈滅
Delay(150);
SPI_RW_Reg(WRITE_REG + STATUS,sta);
}
}
#else //接收 模式代碼
StartUART();
RX_Mode();
Delay(0);//防止編譯警告

while(1)
{
if(nRF24L01_RxPacket(Rx_Buf))
{
for(i=0;i<TX_PLOAD_WIDTH;i++)
R_S_Byte(Rx_Buf[i]);
}
}
#endif
}

㈨ 單片機怎麼用C語言處理接收的數據

處理接收的數據可以先建立一個數組recv[4];
把接收到的數據放裡面,recv[0]對應第一個數據recv[1]對應第2個數據一次類推。
然後電燈可以這樣
P0=recv[0];P1=recv[1];P2=recv[2];P3=recv[3];