Download Reference Manual
The Developer's Library for D
About Wiki Forums Source Search Contact

How to read from serial port?

Moderators: kris

Posted: 07/17/09 14:55:54 Modified: 07/17/09 14:59:44

Hi,I'm a D+Tango newbie.Now,I'm trying to use the serial port on Windows.I can send data via serial port successfully,but I can't read anything from serial port now.I use Vitual Serial Port Driver 6.9 and Hyperterminal to test my program.COM1 and COM2 are virtual port pairs.My program uses COM1 and Hyperterminal listens at COM2.My code is here:

import tango.io.Stdout; 
import tango.io.Console; 
import tango.io.device.SerialPort;
import tango.core.Thread;
 

void main() 
{ 
    SerialPort serCond;
    
    char c;
    bool flag=true;
    
    void readcom()
    {
        Thread thisThread = Thread.getThis; 
        char[] buf;
        int ret;
        while(flag)
        {
            serCond.read(buf);//Read from the COM port.I'm not sure whether it's right.
            Stdout.format("{}",buf);
            Thread.sleep(1.0);   
        }
    }
    
    void sendcom()
    {
        Thread thisThread = Thread.getThis; 
        while(flag)
        {
            serCond.write("Sending data\r\n");//This works fine^_^
            Thread.sleep(1.0);   
        }
    }
    
    void readkey()
    {
        char[] temp;
        Cin.readln(temp);//Just press enter to exit
        flag=false;
        Thread.sleep(1.0);
    }
    
    Stdout("Prepare to use com port").newline;
    serCond = new SerialPort("COM1");
    serCond.speed = 38400;
    serCond.write("Hello world!\r\n");
    
    
    Thread Thread1=new Thread(&readcom);
    Thread1.name="Read Com";
    Thread Thread2=new Thread(&readkey);
    Thread2.name="Wait Input";
    Thread Thread3=new Thread(&sendcom);
    Thread3.name="Write Com";    
    Thread1.start();
    Stdout("Thread1 Started!").newline;
    Thread2.start();
    Stdout("Thread2 Started!").newline;
    Thread3.start();
    Stdout("Thread3 Started!").newline;
    Stdout("Join Thread2...!").newline;
    Thread2.join();
    serCond.close();
    Stdout("You Press Enter!Exit now...").newline;
    
} 

I would appreciate any help in this matter. Thanks!

Author Message

Posted: 07/17/09 21:58:23

serCond.read(buf);//Read from the COM port.I'm not sure whether it's right.

Not quite. The idea is to provide some space for read() to place incoming data, and what you provided is an empty array (of length 0). The read() method also returns the number of bytes consumed, which is probably 0 in this case. You would typically pass a pre-allocated array and use the return value to 'slice' the array in order to trim off unpopulated space. For example:

char[256] tmp;
auto len = input.read (tmp);
if (len != input.Eos)
   {
   Stdout (tmp[0..len]);
   }

Does that help?

Posted: 07/18/09 07:06:31

Ok,it works!Thanks very much!