android 串口通讯3-写个UI测试

uart/res/layout/activity_main.xml内容如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="horizontal" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:background="#000000">


    <TextView 
        android:id="@+id/uart_textview" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="android uart demo" 
        android:textSize="30sp" 
        android:textColor="#ffffffff" 
        android:layout_centerHorizontal="false" 
        android:layout_marginLeft="280dp"
        />


    <ScrollView 


        android:id="@+id/uart_scrollview" 
        android:layout_width="600dp" 
        android:layout_height="300dp" 
        android:layout_marginTop="20dp" 


        android:layout_marginLeft="280dp"
        android:layout_below="@+id/uart_textview"    
        android:background="#ffffffff">


        <TextView
            android:id="@+id/uart_view"
            android:layout_width="280dp"
            android:layout_height="150dp"
            android:textColor="#ff000000"
            android:textSize="20sp" />


    </ScrollView>


    <!--send 编辑区域 -->
    <EditText     
        android:id="@+id/uart_edit" 
        android:layout_width="500dp" 
        android:layout_height="50dp" 
        android:layout_marginTop="10dp"
        android:layout_marginLeft="280dp"
        android:layout_below="@+id/uart_scrollview" 
        android:background="#FFFFFF"
        />


    <!--send 边框 -->
    <Button
        android:id="@+id/uart_button4"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:layout_marginTop="10dp"
        android:layout_toRightOf="@+id/uart_edit"
        android:layout_below="@+id/uart_scrollview"
        android:text="SEND" />


    <!--波特率设置按钮 -->
    <Spinner
        android:id="@+id/uart_mode" 
        android:layout_width="180dp" 
        android:layout_height="45dp" 
        android:layout_below="@+id/uart_textview" 
        android:layout_marginLeft="70dp"
        android:background="#ffffff" 
        android:layout_marginTop="20dp"/>






    <!--打开串口按钮 -->
    <Button 
        android:id="@+id/uart_button0" 
        android:layout_width="180dp" 
        android:layout_height="45dp" 
        android:layout_marginLeft="70dp" 
        android:layout_below="@+id/uart_mode" 
        android:text="openUart"
        android:background="#ffffff" 
        android:layout_marginTop="40dp" />


    <!--clean按钮 -->
    <Button
        android:id="@+id/uart_button2" 
        android:layout_width="180dp" 
        android:layout_height="45dp" 
        android:layout_marginLeft="70dp" 
        android:layout_below="@+id/uart_button0" 
        android:text="clean"
        android:background="#ffffff" 
        android:layout_marginTop="40dp" />


    <!--exit按钮 -->
    <Button
        android:id="@+id/uart_button3" 
        android:layout_width="180dp" 
        android:layout_height="45dp" 
        android:layout_marginLeft="70dp" 
        android:layout_below="@+id/uart_button2" 
        android:text="exit" 
        android:background="#ffffff"
        android:layout_marginTop="40dp" />






</RelativeLayout>





uart/src/com/android/uart/MainActivity.java内容如下:

package com.android.uart;




import java.util.Timer;
import java.util.TimerTask;


import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;


import android.util.Log;


public class MainActivity extends Activity {
 
//定义变量
 TextView view1,view2,view;
 Spinner spinner1;
 String receiveMsg;
 String Msg,ReStr;
 EditText editmsg;
 Button myButton0,myButton2,myButton3,myButton4;
 private boolean sign1;
 public int fd,k=0;
 private static final String TAG = "Serialxxx->";
  
//定义下拉字符串数组 
 private static final String[] countriesStr =
   { "B1200", "B2400", "B4800", "B9600","B19200","B38400","B57600","B115200","B230400","B921600"};


 private static final int[]  baudrate=
   {    1200,    2400,    4800,    9600,   19200,   38400,   57600,   115200,   230400,   921600};
 
 
 private Spinner mySpinner;
 //定义字符串适配器
 private ArrayAdapter<String>  adapter;


 //打开串口,前提是设置了串口波特率
 private Button.OnClickListener myButton0_listener=new Button.OnClickListener()
 {
  //打开函数 uart3
  public void onClick(View arg0) {
   // TODO Auto-generated method stub


 Log.e(TAG, "--open devices ");
      fd=Uartjni.openUart("/dev/ttyS7");
      if(fd>0)
      {
          setTitle("open device sucess!"+String.valueOf(fd));
          Log.e(TAG, "--set  devices baudrate ="+ baudrate[k]);
          Uartjni.setUart(baudrate[k]);
          sign1=true;
      }
      else
      {
          setTitle("open device false!"+fd); 
          sign1=false;
      }
     
      view1.setText("open ttyS7 ");
      


  }


 };
 
 //Clean
 private Button.OnClickListener myButton2_listener=new Button.OnClickListener()
 {
     public void onClick(View v) {
         view.setText(null);
     }


 };
 
 //exit
 private Button.OnClickListener myButton3_listener=new Button.OnClickListener()
 {


     public void onClick(View v) {
         // TODO Auto-generated method stub
         timer.cancel();
         Uartjni.closeUart();
         finish();
         System.exit(0);
     }


 };


 //send
 private Button.OnClickListener myButton4_listener=new Button.OnClickListener()
 {


     public void onClick(View v)
     {
         // TODO Auto-generated method stub
         Msg=editmsg.getText().toString();
         Uartjni.sendMsgUart(Msg);
     }


 };


 //定义时间线程,通过调用本地方法不断接受数据
 Timer timer = new Timer();
 //新建一个定时器任务task
 TimerTask task = new TimerTask()
 {
     public void run() {
         runOnUiThread(new Runnable()  {
             public void run() {


         if (sign1){
               ReStr=Uartjni.receiveMsgUart();
         if(ReStr!=null)
         {
             Log.e(TAG, "-receiveMsguart = "+ ReStr);
             view.append(ReStr);
             view.append("\n");
             ReStr=null;
         }


                 }
             }
         });
     }
 };




//重构onDestroy方法,关闭串口和释放资源


@Override
public void onDestroy()
{
    sign1=false;
    timer.cancel();
    Uartjni.closeUart();
    finish();
}




//实现程序第一次启动时调用的方法onCreate
 @Override
 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);


    //现实布局
     setContentView(R.layout.activity_main);               
    //时间线程调度
     timer.schedule(task, 8000, 8000);


     //获取资源ID,实例化变量,设置编辑框宽度
     mySpinner=(Spinner)findViewById(R.id.uart_mode);
     view1=(TextView)findViewById(R.id.uart_textview);
     view=(TextView)findViewById(R.id.uart_view);
     editmsg=(EditText)findViewById(R.id.uart_edit);
     editmsg.setWidth(200);


     myButton0=(Button)findViewById(R.id.uart_button0);
     myButton2=(Button)findViewById(R.id.uart_button2);
     myButton3=(Button)findViewById(R.id.uart_button3);
     myButton4=(Button)findViewById(R.id.uart_button4);


     //为组件设置监听事件
     myButton0.setOnClickListener(myButton0_listener);   
     myButton2.setOnClickListener(myButton2_listener); 
     myButton3.setOnClickListener(myButton3_listener); 
     myButton4.setOnClickListener(myButton4_listener); 


     //实例化字符串适配器
     adapter = new ArrayAdapter<String>(this,
             android.R.layout.simple_spinner_item, countriesStr);


     //mySpinner绑定适配器
     adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
     mySpinner.setAdapter(adapter);




     //mySpinner的OnItemSelectedListener事件监听,调用本地方法设置串口波特率
     mySpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener()
             {


                 public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
     {
     if(fd>0)
     {
         Log.e(TAG, "setUart baudrate=  "+ arg2);
         //Uartjni.setUart(arg2);
         Uartjni.setUart(baudrate[arg2]);
     }
     else
     {
         k=arg2;
         Log.e(TAG, "select setUart baudrate= "+ arg2);
         arg0.setVisibility(View.VISIBLE);
     }
     }


     public void onNothingSelected(AdapterView<?> arg0)
     {
         // TODO Auto-generated method stub
     }


     });
 }
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 很高兴能回答你的问题。Python可以使用Tkinter来创建带有UI串口通讯程序,可以使用pyserial库来处理串口通讯。你可以从Python官网上获取关于Tkinter的文档,以及关于pyserial的文档。 ### 回答2: Python是一种高级编程语言,拥有丰富的第三方库,能够方便地实现串口通讯程序。以下是一个使用Python编写的带有用户界面的串口通讯程序的简要步骤: 1. 导入必要的库: - serial库:用于连接和控制串口设备。 - tkinter库:用于创建用户界面。 - threading库:用于多线程通信。 2. 创建用户界面: - 使用tkinter库创建一个窗口和相应的控件,如标签、文本框、按钮等。 3. 初始化串口: - 使用serial库,打开需要通信的串口设备,并设置波特率、数据位、停止位、校验等参数。 4. 编写串口读写函数: - 创建一个函数,用于从串口读取数据,并显示在用户界面上。 - 创建另一个函数,用于将用户界面上输入的数据发送到串口设备。 5. 启动线程: - 使用threading库创建两个线程,一个线程用于读取串口数据,另一个线程用于发送串口数据。 - 在用户界面上的按钮事件中启动这两个线程。 6. 创建事件循环: - 在主程序中使用tkinter库的mainloop()函数,启动一个无限循环,用于处理用户界面事件。 以上是一个基本的串口通讯程序的编写步骤,当然在实际开发过程中,可能还需要添加一些错误处理、串口参数设置等功能。希望以上内容对你有所帮助! ### 回答3: 使用Python编写带有用户界面的串口通讯程序可以使用PySerial库和Tkinter库来实现。 首先,需要通过pip安装PySerial库和Tkinter库: ``` pip install pyserial pip install tk ``` 然后,编写一个Python程序,导入PySerial库和Tkinter库,并创建一个窗口: ```python import serial import tkinter as tk window = tk.Tk() window.title("串口通讯程序") ``` 接下来,在窗口中创建串口相关的输入框、按钮和文本框: ```python # 串口号输入框 port_label = tk.Label(window, text="串口号:") port_label.pack(side=tk.LEFT) port_entry = tk.Entry(window) port_entry.pack(side=tk.LEFT) # 波特率输入框 baudrate_label = tk.Label(window, text="波特率:") baudrate_label.pack(side=tk.LEFT) baudrate_entry = tk.Entry(window) baudrate_entry.pack(side=tk.LEFT) # 打开串口按钮 open_btn = tk.Button(window, text="打开串口") open_btn.pack(side=tk.LEFT) # 用于显示串口数据的文本框 output_text = tk.Text(window) output_text.pack() ``` 然后,创建串口对象和相应的串口操作函数,并绑定打开串口按钮的点击事件: ```python serial_port = None def open_serial_port(): global serial_port port = port_entry.get() baudrate = baudrate_entry.get() try: serial_port = serial.Serial(port, baudrate) output_text.insert(tk.END, "成功打开串口\n") except: output_text.insert(tk.END, "无法打开串口\n") open_btn.config(command=open_serial_port) ``` 最后,添加一个循环,使程序能够持续运行,并启动Tkinter的主事件循环: ```python def read_serial_data(): global serial_port while True: if serial_port: data = serial_port.readline().decode() output_text.insert(tk.END, data) window.after(100, read_serial_data) window.mainloop() ``` 这样,一个带有用户界面的串口通讯程序就完成了。用户可以通过界面输入串口号和波特率,并点击打开串口按钮来打开指定的串口。程序会实时监测串口数据,并将读取到的数据显示在文本框中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值