0% found this document useful (0 votes)
127 views14 pages

Sử Dụng Thư Viện Usb Được Cung Cấp Bởi Microchip: Code Dspic18F4500

ádasdasdasdcoong nghe coong nghe coong nghe coong nghe coong nghe coong nghe coong nghe coong nghe coong nghe coong nghe coong nghe coong nghe coong nghe coong nghe coong nghe coong nghe coong nghe coong nghe coong nghe

Uploaded by

anon_196235818
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
127 views14 pages

Sử Dụng Thư Viện Usb Được Cung Cấp Bởi Microchip: Code Dspic18F4500

ádasdasdasdcoong nghe coong nghe coong nghe coong nghe coong nghe coong nghe coong nghe coong nghe coong nghe coong nghe coong nghe coong nghe coong nghe coong nghe coong nghe coong nghe coong nghe coong nghe coong nghe

Uploaded by

anon_196235818
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Code DsPIC18f4500.

S dng th vin USB c cung cp bi Microchip


* File: main.c
* Author:
*
* Created on Ngay 02 thang 8 nam 2012, 12:47
*/
#include "p18f4550.h"
#include "USB/usb.h"
#include "USB/usb_function_hid.h"
#include "HID Device Driver/usb_function_hid.c"
#include "USB/usb_device.h"
#include "usb_device.c"
// CONFIG1L
#pragma config PLLDIV = 5
// PLL Prescaler Selection bits (Divide by 5 (20 MHz oscillator input))
#pragma config CPUDIV = OSC1_PLL2// System Clock Postscaler Selection bits ([Primary Oscillator
Src: /1][96 MHz PLL Src: /2])
#pragma config USBDIV = 2
// USB Clock Selection bit (used in Full-Speed USB mode only;
UCFG:FSEN = 1) (USB clock source comes from the 96 MHz PLL divided by 2)
// CONFIG1H
#pragma config FOSC = HSPLL_HS // Oscillator Selection bits (HS oscillator, PLL enabled (HSPLL))
#pragma config FCMEN = OFF
// Fail-Safe Clock Monitor Enable bit (Fail-Safe Clock Monitor
disabled)
#pragma config IESO = OFF
// Internal/External Oscillator Switchover bit (Oscillator Switchover
mode disabled)
// CONFIG2L
#pragma config PWRT = OFF
// Power-up Timer Enable bit (PWRT disabled)
#pragma config BOR = ON
// Brown-out Reset Enable bits (Brown-out Reset enabled in
hardware only (SBOREN is disabled))
#pragma config BORV = 3
// Brown-out Reset Voltage bits (Minimum setting)
#pragma config VREGEN = OFF // USB Voltage Regulator Enable bit (USB voltage regulator
disabled)
// CONFIG2H
#pragma config WDT = OFF
// Watchdog Timer Enable bit (WDT disabled (control is placed on
the SWDTEN bit))
#pragma config WDTPS = 32768 // Watchdog Timer Postscale Select bits (1:32768)
// CONFIG3H
#pragma config CCP2MX = ON
// CCP2 MUX bit (CCP2 input/output is multiplexed with RC1)
#pragma config PBADEN = OFF // PORTB A/D Enable bit (PORTB<4:0> pins are configured as
digital I/O on Reset)
#pragma config LPT1OSC = OFF // Low-Power Timer 1 Oscillator Enable bit (Timer1 configured for
higher power operation)
#pragma config MCLRE = ON
// MCLR Pin Enable bit (MCLR pin enabled; RE3 input pin
disabled)

// CONFIG4L
#pragma config STVREN = ON
// Stack Full/Underflow Reset Enable bit (Stack full/underflow will
cause Reset)
#pragma config LVP = ON
// Single-Supply ICSP Enable bit (Single-Supply ICSP enabled)
#pragma config ICPRT = OFF
// Dedicated In-Circuit Debug/Programming Port (ICPORT) Enable
bit (ICPORT disabled)
#pragma config XINST = OFF
// Extended Instruction Set Enable bit (Instruction set extension and
Indexed Addressing mode disabled (Legacy mode))
// CONFIG5L
#pragma config CP0 = OFF
protected)
#pragma config CP1 = OFF
protected)
#pragma config CP2 = OFF
protected)
#pragma config CP3 = OFF
protected)
// CONFIG5H
#pragma config CPB = OFF
not code-protected)
#pragma config CPD = OFF
protected)
// CONFIG6L
#pragma config WRT0 = OFF
protected)
#pragma config WRT1 = OFF
protected)
#pragma config WRT2 = OFF
protected)
#pragma config WRT3 = OFF
protected)

// Code Protection bit (Block 0 (000800-001FFFh) is not code// Code Protection bit (Block 1 (002000-003FFFh) is not code// Code Protection bit (Block 2 (004000-005FFFh) is not code// Code Protection bit (Block 3 (006000-007FFFh) is not code-

// Boot Block Code Protection bit (Boot block (000000-0007FFh) is


// Data EEPROM Code Protection bit (Data EEPROM is not code-

// Write Protection bit (Block 0 (000800-001FFFh) is not write// Write Protection bit (Block 1 (002000-003FFFh) is not write// Write Protection bit (Block 2 (004000-005FFFh) is not write// Write Protection bit (Block 3 (006000-007FFFh) is not write-

// CONFIG6H
#pragma config WRTC = OFF
// Configuration Register Write Protection bit (Configuration
registers (300000-3000FFh) are not write-protected)
#pragma config WRTB = OFF
// Boot Block Write Protection bit (Boot block (000000-0007FFh) is
not write-protected)
#pragma config WRTD = OFF
// Data EEPROM Write Protection bit (Data EEPROM is not writeprotected)
// CONFIG7L
#pragma config EBTR0 = OFF
// Table Read Protection bit (Block 0 (000800-001FFFh) is not
protected from table reads executed in other blocks)
#pragma config EBTR1 = OFF
// Table Read Protection bit (Block 1 (002000-003FFFh) is not
protected from table reads executed in other blocks)
#pragma config EBTR2 = OFF
// Table Read Protection bit (Block 2 (004000-005FFFh) is not
protected from table reads executed in other blocks)

#pragma config EBTR3 = OFF


// Table Read Protection bit (Block 3 (006000-007FFFh) is not
protected from table reads executed in other blocks)
// CONFIG7H
#pragma config EBTRB = OFF
// Boot Block Table Read Protection bit (Boot block (0000000007FFh) is not protected from table reads executed in other blocks)

unsigned char outbuffer[HID_OUT_SIZE];


unsigned char inbuffer[HID_IN_SIZE];
USB_HANDLE USBOutHandle = 0;
USB_HANDLE USBInHandle = 0;
void high_isr(void);
void low_isr(void);
#pragma code low_vector=0x18
void interrupt_at_low_vector(void)
{
_asm GOTO low_isr _endasm
}
#pragma code
#pragma code high_vector=0x8
void interrupt_at_high_vector(void)
{
_asm GOTO high_isr _endasm
}
#pragma code
#pragma interrupt high_isr
void high_isr()
{
#if defined(USB_INTERRUPT)
USBDeviceTasks();
#endif
}
#pragma interruptlow low_isr
void low_isr()
{
}
static void InitializeSystem(void) {
ADCON1 |= 0x0F;
TRISC = 0;
LATC = 0;
USBDeviceInit();

}
BOOL red, green;
void main() {
InitializeSystem();
red = FALSE;
green = FALSE;
#if defined(USB_INTERRUPT)
USBDeviceAttach();
#endif
//TRISDbits.TRISD0 = 0; //set portD pin 3 (red LED) to output
TRISCbits.RC7 = 0; //
LATCbits.LATC7 = 0;
TRISD = 0x0F; // Set 4 bit port D input;
LATD = 0x00; // turn off port D;
PORTD = 0x00;

while (1) {
if(!((USBDeviceState < CONFIGURED_STATE)||(USBSuspendControl==1))) {
if(!HIDRxHandleBusy(USBOutHandle))
{
if (outbuffer[0] == 0) {
if(!HIDTxHandleBusy(USBInHandle))
{
inbuffer[0] = PORTD;
USBInHandle = HIDTxPacket(HID_EP,(BYTE*)&inbuffer[0], HID_IN_SIZE);
}
}
if (outbuffer[0] == 1) {
LATCbits.LATC7 = !LATCbits.LATC7; //Turn portB pin 3 (red LED) to high
}
USBOutHandle = HIDRxPacket(HID_EP, (BYTE*)&outbuffer, HID_OUT_SIZE);
}
}
}
}
BOOL USER_USB_CALLBACK_EVENT_HANDLER(int event, void *pdata, WORD size)
{
switch(event)
{
case EVENT_CONFIGURED:

USBEnableEndpoint(HID_EP,USB_IN_ENABLED|USB_OUT_ENABLED|USB_HANDSHAKE_ENAB
LED|USB_DISALLOW_SETUP);
USBOutHandle = HIDRxPacket(HID_EP,(BYTE*)&outbuffer, HID_OUT_SIZE);
break;
case EVENT_EP0_REQUEST:
USBCheckHIDRequest();
break;
default:
break;
}
return TRUE;
}

Code C# to giao din ngi dng

Th vin HIDlib ca microchip v USB


using
using
using
using
using
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;
HIDLib;
System.IO;
System.Net;
System.Net.Sockets;
System.Threading;

namespace Usb_example
{
public partial class Form1 : Form
{
private const int BUFFER_SIZE = 1024;
private const int PORT_NUMBER = 8888;
String datasend = "1";
String datarequest = "0";
Boolean ok = false;
Boolean ok1 = false;
Boolean ok2 = false;
HIDDevice dev = new HIDDevice();
public Form1()
{
InitializeComponent();
dev.vid = 0x04D8;
dev.pid = 0x003f;
dev.in_size = 2;
dev.out_size = 3;
dev.Initialize();
}

private void Form1_Load(object sender, EventArgs e)


{
}
private Boolean send()
{
if (dev.AttachedState)
{
byte[] data = new byte[3];
data[0] = 1;
if (!dev.Transmit(data)) MessageBox.Show("Error");
return true;
}
else txt.AppendText("USB khng kt ni \n");
return false;
}
private String request()
{
if (dev.AttachedState)
{
byte[] request = new byte[3];
request[0] = 0;
dev.Transmit(request);
byte[] result = dev.Receive();
txt.AppendText( "T USB : "+
Convert.ToString(result[0],2).PadLeft(8,'0') +"\n");
return result[0].ToString();
}
txt.AppendText("USB khng kt ni \n");
return "xx";
}
private void btn_Click(object sender, EventArgs e)
{
send();
return;
}
protected override void WndProc(ref Message m)
{
dev.DeviceChange(ref m);
base.WndProc(ref m);
}
private void button1_Click(object sender, EventArgs e)
{
request();
return;
}
private void startsv_Click(object sender, EventArgs e)
{
if (startsv.Text == "Start server")
{
txt.AppendText("\n");
startsv.Text = "Stop server";
ok = true;

hostget.Enabled = false;
hostsend.Enabled = false;
}
else
{
startsv.Text = "Start server";
ok = false;
txt.AppendText("Tt server . Chuyn sang ch iu khin t my
tnh \n");
hostget.Enabled = true;
hostsend.Enabled = true;
}
Thread t = new Thread(new ThreadStart( tsever ));
t.IsBackground = true;
t.Start();

}
private void tsever()
{
try
{
//IPAddress address = IPAddress.Parse("192.168.1.103");

IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());


string IP4Address = String.Empty;
foreach (IPAddress IPA in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (IPA.AddressFamily == AddressFamily.InterNetwork)
{
IP4Address = IPA.ToString();
break;
}
}

TcpListener listener = new


TcpListener(IPAddress.Parse(IP4Address), PORT_NUMBER);
// 1. listen
if (ok == false)
{
listener.Stop(); return;
}
else
{
txt.AppendText("Server khi to a ch " +
listener.LocalEndpoint + "\n");
txt.AppendText("i kt ni... \n");
listener.Start();
}

//Console.WriteLine("Server started on " +


listener.LocalEndpoint);
//Console.WriteLine("Waiting for a connection...");
while (true)
{
// 2. receive

Socket socket = listener.AcceptSocket();


txt.AppendText("C kt ni t a ch " +
socket.RemoteEndPoint + "\n");
//Console.WriteLine("Connection received from " +
socket.RemoteEndPoint);
var stream = new
var reader = new
var writer = new
writer.AutoFlush

NetworkStream(socket);
StreamReader(stream);
StreamWriter(stream);
= true;

while (true)
{
try
{
string str = reader.ReadLine();
txt.AppendText(str);
txt.AppendText("\n");
if (str == datasend)
{
if (!send()) { writer.WriteLine("xx"); };
}
if (str == "123456")
{
txt.AppendText("bye \n");
break;
}
if (str == datarequest)
{
writer.WriteLine(request());
}
}
catch (Exception e)
{
txt.AppendText("in thoi ngt kt ni \n");
//txt.AppendText(reader.ToString());
stream.Close();
reader.Close();
writer.Close();
break;
}
}

}
// 4. close
listener.Stop();
hostget.Enabled = true;
hostsend.Enabled = true;
txt.AppendText("Tt server \n");
}
catch (Exception ex)
{
//Console.WriteLine("Error: " + ex);
//txt.AppendText("Error: " + ex);
//startsv.Text = " Start server ";
//hostget.Enabled = true;
//hostsend.Enabled = true;
}
//Console.Read();
}

}
}

Lp trnh Android
package com.example.android_socket;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener
EditText serverForm;
EditText portForm;
Button sendButton;
Button conDisButton;
Button getButton;
TextView result;
ScrollView scr;

boolean isConnect=false;
Socket socket;
volatile DataOutputStream dos = null;
volatile DataInputStream dis = null;
volatile BufferedReader br = null;
String datasend = "1\n";
String datarequest = "0\n";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serverForm = (EditText) findViewById(R.id.serverForm);
portForm =(EditText) findViewById(R.id.portForm);
sendButton = (Button) findViewById(R.id.send);
getButton = (Button) findViewById(R.id.get);
conDisButton = (Button) findViewById(R.id.condis);
result = (TextView) findViewById(R.id.result);
scr = (ScrollView) findViewById(R.id.scrollView1);
sendButton.setOnClickListener(this);
sendButton.setOnClickListener(this);
conDisButton.setOnClickListener(this);
getButton.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.condis)
{
if(isConnect) {
disconnectTask dis = new disconnectTask();
dis.execute();
}
else{
int port;
String serverName = serverForm.getText().toString();
String portString = portForm.getText().toString();
if( (serverName == "") || ( portString == "" ) )
{
Toast.makeText(this, "please fill server and port
form",
Toast.LENGTH_SHORT).show();
return;
}
try{

port = Integer.parseInt(portString);
if(port<0||port>64000)
throw new Exception();
}
catch(Exception e){
Toast.makeText(this, "Port must be integer and in
range 0-64000",
Toast.LENGTH_SHORT).show();
return;
}
connectTask t = new connectTask(serverName, port);
t.execute();
}
}
else
if (v.getId() == R.id.send)
{
sendTask t= new sendTask(datasend);
t.start();
}
else if (v.getId() == R.id.get)
{
sendTask t= new sendTask(datarequest);
t.start();
}
}
class connectTask extends AsyncTask<Void, Void, Boolean> {
String serverString;
int port;
public connectTask(String server,int port){
this.serverString = server;
this.port = port;
}
@Override
protected void onPreExecute() {
conDisButton.setEnabled(false);
}
@Override
protected Boolean doInBackground(Void... params) {
isConnect=false;
try {
Log.e("TEST", "thu cai");
socket = new Socket();
socket.connect(new InetSocketAddress(serverString,
port), 1500);
Log.e("TEST", "khong dung");
} catch (UnknownHostException e) {
displayResult("\n Error: Unknown host name!");
return false;
} catch (IOException e) {
displayResult("\n Error:"+e.getMessage());
return false;
}

displayResult("\n Connect to server success!");


isConnect=true;
return true;
}
@Override
protected void onPostExecute(Boolean result) {
if(result){
conDisButton.setText("Disconnect");
receiveTask t=new receiveTask();
t.start();
}
conDisButton.setEnabled(true);
}

}
class disconnectTask extends AsyncTask<Void, Void, Boolean>
{
@Override
protected void onPreExecute() {
conDisButton.setEnabled(false);
}
@Override
protected Boolean doInBackground(Void... params) {
isConnect=false;
try{
if(socket!=null){
socket.close();
socket=null;
}
if(dos!=null){
dos.close();
dos=null;
}
if(dis!=null){
dis.close();
dis=null;
}
if(br!=null){
br.close();
br=null;
}
}
catch(Exception e){
displayResult("\n Error: "+e.getMessage());
conDisButton.setEnabled(true);
return false;
}
displayResult("\n Disconnected");
return true;
}
@Override
protected void onPostExecute(Boolean result) {
if(result)
conDisButton.setText("Connect");
conDisButton.setEnabled(true);

}
class sendTask extends Thread
{
String data;
public sendTask(String dataa)
{
this.data=dataa;
}
@Override
public void run() {
if(!isConnect){
displayResult("\n Senderror: not connected");
return;
}
try {
dos=new DataOutputStream(socket.getOutputStream());
Log.e("Test", data);
dos.writeBytes(data);
} catch (IOException e) {
displayResult("\n send data to server failed!");
return;
}
displayResult("\n Send data to server success!");
}
}
class receiveTask extends Thread {
@Override
public void run() {
if(!isConnect){
displayResult("\n Senderror: not connected");
return;
}
String response=null;
try {
br=new BufferedReader(new
InputStreamReader(socket.getInputStream()));
while (isConnect&&(response = br.readLine()) != null)
{
Log.e("test12345", response);
if (!response.contains("xx"))
{
int ss = Integer.parseInt(response);
displayResult("\n Trng thi n LED: "+
Integer.toString(ss, 2));
try{
Thread.sleep(100);
}catch(Exception e){};
}

else displayResult("\n USB cha c kt ni");


}
} catch (IOException e) {
//displayResult("\n ReceiveError: Error on Receive
response from server!");
return;
}
}
}
private void displayResult(final String resultText)
{
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run()
{
result.append(resultText);
//Log.e("test1234",Integer.toString(
result.getHeight() ) );
scr.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
scr.fullScroll(View.FOCUS_DOWN);
}
});
}
});
}
}

You might also like