2013-05-29 1 views
1

Я новичок в netduino, поэтому у меня есть простой вопрос (или, это должно быть просто). Что я хочу сделать, это отправить целое число (string) через rs232 из моего приложения winform в мой netduino plus 2, а затем мой netduino должен прочитать это целое число и мигать на борту, что много раз.Netduino связь с ПК

Я прочитал онлайн-учебник по этой теме и нашел несколько примеров, которые должны обеспечить связь между моим компьютером и Netduino.

Да, я получил от него эхо. Я получаю эхо, даже если я отключу свой netduino и спрячу его в кармане :). Так много для моего понимания этого гаджета.

Как я могу отправить информацию на мой Netduino через кабель rs232, который он может читать, понимать и действовать соответствующим образом?

Существует код прямо из сети:

Для Netduino:

using System; 
using System.Net; 
using System.Net.Sockets; 
using System.Threading; 
using Microsoft.SPOT; 
using Microsoft.SPOT.Hardware; 
using SecretLabs.NETMF.Hardware; 
using SecretLabs.NETMF.Hardware.Netduino; 
using System.IO.Ports; 

namespace NetduinoApplication1 
{ 
public class Program 
{ 
    static SerialPort serial; 

    public static void Main() 
    { 
     // initialize the serial port for COM1 (using D0 & D1) 
     serial = new SerialPort(SerialPorts.COM1, 9600, Parity.None, 8, StopBits.One); 
     // open the serial-port, so we can send & receive data 
     serial.Open(); 
     // add an event-handler for handling incoming data 
     serial.DataReceived += new SerialDataReceivedEventHandler(serial_DataReceived); 
     OutputPort led = new OutputPort(Pins.ONBOARD_LED, false); 
     for (int i = 0; i < 3; i++) 
     { 
      led.Write(true); // turn on the LED 
      Thread.Sleep(250); // sleep for 250ms 
      led.Write(false); // turn off the LED 
      Thread.Sleep(250); // sleep for 250ms 

     } 

     // wait forever... 
     Thread.Sleep(Timeout.Infinite); 
    } 

    static void serial_DataReceived(object sender, SerialDataReceivedEventArgs e) 
    { 

     // create a single byte array 
     byte[] bytes = new byte[1]; 

     // as long as there is data waiting to be read 
     while (serial.BytesToRead > 0) 
     { 
      // read a single byte 
      serial.Read(bytes, 0, bytes.Length); 
      // send the same byte back 

      serial.Write(bytes, 0, bytes.Length); 
      OutputPort led1 = new OutputPort(Pins.ONBOARD_LED, false); 
      led1.Write(true); // turn on the LED 
      Thread.Sleep(250); // sleep for 250ms 
      led1.Write(false); // turn off the LED 
      Thread.Sleep(250); // sleep for 250ms 

     } 

    } 

} 
} 

И код для моей консоли:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.IO.Ports; 

namespace ConsoleRSS 
{ 
class Program 
{ 
    static SerialPort serial; 
    static void Main(string[] args) 
    { 
     // provide some usage information 
     System.Console.WriteLine("enter some text and hit ENTER."); 
     System.Console.WriteLine("enter 'x' and hit ENTER to exit."); 
     System.Console.WriteLine(); 

     // initialize the serial port for COM3 (could be other port, depends on system) 
     serial = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One); 
     // open the serial-port, so we can send & receive data 
     serial.Open(); 
     // add an event-handler for handling incoming data 
     serial.DataReceived += new SerialDataReceivedEventHandler(serial_DataReceived); 

     // this will hold each line entered 
     string line = string.Empty; 

     // as long as an x is not entered 
     while (line.ToLowerInvariant() != "x") 
     { 
      // read a single line from the console 
      line = System.Console.ReadLine(); 

      // convert the line to bytes 
      byte[] utf8Bytes = System.Text.Encoding.UTF8.GetBytes(line); 

      // send the bytes over the serial-port 
      serial.Write(utf8Bytes, 0, utf8Bytes.Length); 
     } 
    } 
    static void serial_DataReceived(object sender, SerialDataReceivedEventArgs e) 
    { 
     // wait a little for the buffer to fill 
     System.Threading.Thread.Sleep(100); 

     // create an array for the incoming bytes 
     byte[] bytes = new byte[serial.BytesToRead]; 
     // read the bytes 
     serial.Read(bytes, 0, bytes.Length); 
     // convert the bytes into a string 
     string line = System.Text.Encoding.UTF8.GetString(bytes); 

     // write the received bytes, as a string, to the console 
     System.Console.WriteLine("echo: " + line); 
     System.Console.WriteLine(); 
    } 

} 
} 
+0

Можете ли вы показать какой-то код того, что вы пробовали? это пример, который вы попробовали? http://www.instructables.com/id/Serial-Port-Programming-With-NET/ – tay10r

+0

Возможно, вы и автор этого сообщения: http://stackoverflow.com/questions/16623915/how-to-send- a-signal-to-run-a-machine-using-netduino должен говорить :) Довольно похожая проблема ... – user2019047

ответ

0

Я не уверен, что проблема вас на самом деле с этим справляются? Ваш код на первый взгляд выглядит правильно.

Я бы попробовал сначала проверить ваше оборудование, так как кабель USB фактически установлен как COM 1 в диспетчере устройств на вашем ПК? Кабель подключен к правильным портам в netduino?