|
环境:
GTK:gtk-win32-devel-2.8.6-rc3
下载地址:http://gladewin32.sourceforge.net/
串口内容:用GPSGATE这个软件模拟的。
IDE:DEV CPP(安装好gtk-win32-devel-2.8.6-rc3.exe会自动配置)
刚才试了一下GTK在WINDOWS中读串口数据,也不知道是不是火星的内容。
PS.这好像是我的第一个技术类的帖子.
GTK在WINDOWS下读取串口,使用g_io_channel_new_file函数即可,将该函数的第一个参数const gchar *filename设为要读取的端口即可。主要步骤如下:
GIOChannel* chan=NULL;
guint source_id ;
用下面的函数打开com8
chan = g_io_channel_new_file ("com8","r",&err);
把文件描述符可读的事件加入到程序的事件循环中,accept_cb为回调函数的名称。
source_id = g_io_add_watch( chan,
(GIOCondition)(G_IO_IN ),
accept_cb,
NULL);
accept_cb回调函数的内容
gboolean accept_cb(GIOChannel* iochannel, GIOCondition condition, gpointer data)
{
gchar *buf;
gsize *length;
GError *error=NULL;
//g_io_channel_read_to_end (iochannel,&buf,length,&error);
g_io_channel_read_line (chan, &buf, NULL, NULL, &error);
if (error != NULL) {
g_error ("%s", error->message);
g_free(error);
}
else
{
g_print(buf);
g_free(buf);
}
return TRUE;
}
通过g_io_channel_read_line函数读取串口的内容,内容被放到变量buf中。
刚开始我用g_io_channel_read_to_end读内容,但发现会停在这里。
全部代码,代码显示一个仅包括HELLO WORLD按钮的窗口,在DOS窗口中会输出串口读到的内容:
#include <stdio.h>
#include <gtk/gtk.h>
GIOChannel* chan=NULL;
guint source_id ;
gboolean accept_cb(GIOChannel* iochannel, GIOCondition condition, gpointer data)
{
gchar *buf;
gsize *length;
GError *error=NULL;
//g_io_channel_read_to_end (iochannel,&buf,length,&error);
g_io_channel_read_line (chan, &buf, NULL, NULL, &error);
if (error != NULL) {
g_error ("%s", error->message);
g_free(error);
}
else
{
g_print(buf);
g_free(buf);
}
return TRUE;
}
void hello( GtkWidget *widget,
gpointer data )
{
g_print ("Hello World\n");
}
void destroy( GtkWidget *widget,
gpointer data )
{
g_printf("Free IO Channel\n");
if(chan !=NULL)
{
g_source_remove (source_id);
g_io_channel_close(chan);
}
gtk_main_quit ();
}
int main( int argc,
char *argv[] )
{
GtkWidget *window;
GtkWidget *button;
GError *err = NULL;
gchar *data;
gtk_init (&argc, &argv);
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
g_signal_connect (G_OBJECT (window), "delete_event",
G_CALLBACK (destroy), NULL);
g_signal_connect (G_OBJECT (window), "destroy",
G_CALLBACK (destroy), NULL);
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
button = gtk_button_new_with_label ("Hello World");
g_signal_connect (G_OBJECT (button), "clicked",
G_CALLBACK (hello), NULL);
gtk_container_add (GTK_CONTAINER (window), button);
gtk_widget_show (button);
gtk_widget_show (window);
//串口打开
chan = g_io_channel_new_file ("com8","r",&err);
if (!chan) {
g_warning ("Failed to open %s: %s\n",
"com8", err->message);
g_error_free (err);
}
else
{
source_id = g_io_add_watch( chan,
(GIOCondition)(G_IO_IN ),
accept_cb,
NULL);
}
gtk_main ();
return 0;
} |
|