我用delphi和单片机进行串口通信,在串口调试助手里通过,但实际硬件通讯时,不能接收数据。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我用delphi和单片机进行串口通信,在串口调试助手里通过,但实际硬件通讯时,不能接收数据。相关的知识,希望对你有一定的参考价值。
procedure TForm1.FormCreate(Sender: TObject);
begin
MSComm1.CommPort:=1;
MSComm1.Settings:='9600,n,8,1';
MSComm1.InBufferCount:=0;
MSComm1.InputLen:=0;
MSComm1.InputMode:=ComInputModeBinary; //ComInputModeText
MSComm1.RThreshold:=1;
// MSComm1.PortOpen:=true;
end;
procedure TForm1.Button4Click(Sender: TObject);
var
send:olevariant;
count,i:integer;
begin
count:=1;
send:=vararraycreate([0,count-1],varbyte);
for i:= 0 to count-1 do
send[i]:=10;
if MSComm1.PortOpen=false then
MSComm1.PortOpen:=true;
MSComm1.Output:=send;
end;
procedure TForm1.MSComm1Comm(Sender: TObject);
var
recstr:Olevariant;
begin
if MSComm1.CommEvent=2 then
begin
recstr:=MSComm1.Input;
end;
edit1.Text:=inttostr(recstr[0]);
//edit2.Text:=inttostr(recstr[1]);
//edit3.Text:=inttostr(recstr[2]);
//edit4.Text:=inttostr(recstr[3]);
end;
单片机得程序如下,用的是atmega16l,晶振是4M
#include <iom16v.h>
#include <macros.h>
unsigned char dat[4]=0,0,255,255;//0,0,0xA,
unsigned char temp;
void port_init(void)
PORTA = 0x00;
DDRA = 0x00;
PORTB = 0x00;
DDRB = 0x00;
PORTC = 0x00; //m103 output only
DDRC = 0x00;
PORTD = 0xFF;
DDRD = 0x02;
//UART0 initialize
// desired baud rate: 9600
// actual: baud rate:9615 (0.2%)
void uart0_init(void)
UCSRB = 0x00; //disable while setting baud rate
UCSRA = 0x02;
UCSRC = BIT(URSEL) | 0x06;
UBRRL = 0x33; //set baud rate lo
UBRRH = 0x00; //set baud rate hi
UCSRB = 0x98;
void uart0_send(unsigned char i)
while(!(UCSRA & (1<<UDRE)));
UDR=i;
void str_send(unsigned char *s)
while(*s)
uart0_send(*s);
s++;
#pragma interrupt_handler uart0_rx_isr:iv_USART0_RXC
void uart0_rx_isr(void)
//uart has received a character in UDR
temp=UDR;
//call this routine to initialize all peripherals
void init_devices(void)
//stop errant interrupts until set up
CLI(); //disable all interrupts
port_init();
uart0_init();
MCUCR = 0x00;
GICR = 0x00;
TIMSK = 0x00; //timer interrupt sources
SEI(); //re-enable interrupts
//all peripherals are now initialized
//
void main(void)
unsigned char i;
init_devices();
//insert your functional code here...
while(1)
if(temp==0x0A)
SREG=0;
for(i=0;i<4;i++)
uart0_send(dat[i]);
temp=0;
SEI();
//while(1);
以上是关于我用delphi和单片机进行串口通信,在串口调试助手里通过,但实际硬件通讯时,不能接收数据。的主要内容,如果未能解决你的问题,请参考以下文章