[英]C# Serial Port + CCS C Serial Port + PIC 16F877A
我有一個PIC 16F887A連接到串行端口。 我希望它在收到0x01時亮起綠色指示燈,而從PC收到0x00時亮起紅色指示燈。 我從C#Windows窗體應用程序發送字符,PIC本身是使用CCS C編程的。您能告訴我我在做什么錯嗎,因為下面的代碼不起作用?
編輯:通過不起作用,我的意思是在兩種情況下它都會點亮紅色指示燈。
C#代碼
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
namespace deneme
{
public partial class Form1 : Form
{
SerialPort port = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One);
public Form1()
{
InitializeComponent();
}
private void openportbtn_Click(object sender, EventArgs e)
{
if (port.IsOpen)
{
port.Close();
}
if (!port.IsOpen)
{
port.Open();
}
}
private void rightbtn_Click(object sender, EventArgs e)
{
byte[] right = new byte[1];
right[0] = 0x01;
port.Write(right, 0, right.Length);
}
private void wrongbtn_Click(object sender, EventArgs e)
{
byte[] wrong = new byte[1];
wrong[0] = 0x00;
port.Write(wrong, 0, wrong.Length);
}
}
}
CCS C代碼
#include <16f877A.h>
#fuses XT,NOWDT,NOPROTECT,NOBROWNOUT,NOLVP,NOPUT,NOWRT,NODEBUG,NOCPD
#use delay (clock=4000000)
#use rs232 (baud=9600, xmit=pin_c6, rcv=pin_c7, parity=N, stop=1, bits=8)
char received;
char right = 0x01;
#int_rda
void serial_interrupt()
{
disable_interrupts(int_rda);
received = getc();
if(received == right)
{
output_high(pin_c5); //green led
delay_ms(200);
output_low(pin_c5);
}
else
{
output_high(pin_c4); //red led
delay_ms(200);
output_low(pin_c4);
}
}
void main()
{
setup_psp(PSP_DISABLED);
setup_timer_1(T1_DISABLED);
setup_timer_2(T2_DISABLED,0,1);
setup_adc_ports(NO_ANALOGS);
setup_adc(ADC_OFF);
setup_CCP1(CCP_OFF);
setup_CCP2(CCP_OFF);
output_low(pin_c4);
output_low(pin_c5);
enable_interrupts(GLOBAL);
while(1)
{
enable_interrupts(int_rda);
}
}
如果在兩種情況下均收到0x00,則可能是波特率不匹配,甚至很小。 在檢測到起始位之后,PIC可能會看到前7個零,並認為它看到了8,在兩種情況下都為0x00。 我會嘗試從PIC和PC進行傳輸,並觀察示波器上的線路,以確保它們以相同的速度運行。 您也可以嘗試連續發送0xAA以獲得眼圖(10101010)並比較兩個信號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.