Joeyos's Blog Software Engineer

java读取串口数据并绘图

2018-05-10
Quan Zhang

这里java的JDK版本为1.8.0X,串口为COM3

将RXTXcomm.jar复制到\jre\lib\ext目录下。

到eclipse中右击项目—>Build Path—> Configure Build Path –> Libraries –> Add External JARs…—>找到/jre/lib/ext目录下的RXTXcomm.jar--->打开-->OK。

读取串口数据

package com.spilltest.serial;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.TooManyListenersException;
import gnu.io.*;
import java.sql.*;
import java.text.SimpleDateFormat;

public class SerialTool extends Thread implements SerialPortEventListener {

	static CommPortIdentifier portId;//端口标识
	static Enumeration<?> portList;//所有端口
	InputStream inputStream;
	static OutputStream outputStream;
	static SerialPort serialPort;
	public static String s = "";

	Chart_test Drawmap = new Chart_test();//画图类

	@Override
	/**
	 */
	public void serialEvent(SerialPortEvent event) {

		switch (event.getEventType()) {

		case SerialPortEvent.BI:
		case SerialPortEvent.OE:
		case SerialPortEvent.FE:
		case SerialPortEvent.PE:
		case SerialPortEvent.CD:
		case SerialPortEvent.CTS:
		case SerialPortEvent.DSR:
		case SerialPortEvent.RI:
		case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
			break;
		case SerialPortEvent.DATA_AVAILABLE:

			byte[] readBuffer = new byte[1];
			try {
				int numBytes = -1;
				while (inputStream.available() > 0) {

					numBytes = inputStream.read(readBuffer);

					if (numBytes > 0) {
						int BufferValue = readBuffer[0] & 0xFF;//16进制转10进制
						System.out.println("串口数据:" + BufferValue);
						Drawmap.setMapValue(BufferValue);//画图数据
						try   
						{   
							Thread.currentThread().sleep(100);//等待画图
						}   
						catch(Exception e){}  
						/*
						// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
						// SqlStart++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
						// 驱动程序名
						String driver = "com.mysql.jdbc.Driver";
						// URL指向要访问的数据库名scutcs
						String url = "jdbc:mysql://127.0.0.1:3306/scutcs";
						// MySQL配置时的用户名
						String user = "root";
						// MySQL配置时的密码
						String password = "zhang110";
						try {
							// 加载驱动程序
							Class.forName(driver);
							// 连续数据库
							Connection conn = DriverManager.getConnection(url, user, password);
							if (!conn.isClosed())
								System.out.println("Succeeded connecting to the Database!");
							// pstatement用来执行SQL语句
							// 1.创建数据表SQL语句
							String sql_create = "create table if not exists databasic" + "(dtime varchar(19) not null,"
									+ "ddata varchar(4) not null);";
							// + "primary key(dtime));";
							PreparedStatement pstatementCreate = conn.prepareStatement(sql_create);
							// 执行SQL语句
							int rs_create = pstatementCreate.executeUpdate();
							PreparedStatement pstatement = conn.prepareStatement("insert into databasic values(?, ?)");
							Date time = new Date();
							SimpleDateFormat tf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							pstatement.setString(1, tf.format(time));
							String str = new String(readBuffer);
							pstatement.setString(2, str);
							pstatement.executeUpdate();
//							// 2.查询数据表
//							 String sql_select = "select * from databasic"; ResultSet rs_select =
//							 pstatement.executeQuery(sql_select);
//							 System.out.println("-----------------------------------------------------");
//							 System.out.println("执行结果如下所示:");
//							 System.out.println("-----------------------------------------------------");
//							 System.out.println(" 时间" + "\t" + "\t" + "\t" + " 数据");
//							 System.out.println("-----------------------------------------------------");
//							 String dtime = null; String ddata = null; while(rs_select.next()) { // 选择数据
//							 dtime = rs_select.getString("dtime"); ddata = rs_select.getString("ddata");
//							 // 输出结果 System.out.println(dtime + "\t" + ddata); }
//							// rs_select.close();
							conn.close();
						} catch (ClassNotFoundException e) {
							System.out.println("Sorry,can't find the Driver!");
							e.printStackTrace();
						} catch (SQLException e) {
							e.printStackTrace();
						} catch (Exception e) {
							e.printStackTrace();
						}
						// SqlEnd++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
						*/
						readBuffer = new byte[1];
					}
				}
				Drawmap.setMapValue(0);//画图数据
			} catch (IOException e) {
			}
			break;
		}
	}

	/**
	 * 
	 * 
	 * @return
	 */
	public int startComPort() {
		portList = CommPortIdentifier.getPortIdentifiers();
		while (portList.hasMoreElements()) {
			portId = (CommPortIdentifier) portList.nextElement();
			System.out.println("设备类型--->" + portId.getPortType());
			System.out.println("串口名称---->" + portId.getName());
			s = s + "设备类型--->" + portId.getPortType() + '\n' + portId.getName() + '\n';
			if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
				if (portId.getName().equals("COM3")) {
					try {
						serialPort = (SerialPort) portId.open("COM_3", 9600);
					} catch (PortInUseException e) {
						e.printStackTrace();
						return 0;
					}
					try {
						inputStream = serialPort.getInputStream();
						outputStream = serialPort.getOutputStream();
					} catch (IOException e) {
						e.printStackTrace();
						return 0;
					}
					try {
						serialPort.addEventListener(this);
					} catch (TooManyListenersException e) {
						e.printStackTrace();
						return 0;
					}
					serialPort.notifyOnDataAvailable(true);
					try {
						serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
								SerialPort.PARITY_NONE);
					} catch (UnsupportedCommOperationException e) {
						e.printStackTrace();
						return 0;
					}
					return 1;
				}
			}
		}
		return 0;
	}

	public static void main(String[] args) {
		SerialTool cRead = new SerialTool();
		int i = cRead.startComPort();
		if (i == 1) {
			cRead.start();
			try {
				String st = "";
				System.out.println("" + st.getBytes("gbk").length);
				outputStream.write(st.getBytes("gbk"), 0, st.getBytes("gbk").length);
			} catch (IOException e) {

				e.printStackTrace();
			}
		} else {
			return;
		}
	}
}

画波形图

package com.spilltest.serial;

import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Chart_test extends JFrame {

	private List<Integer> values;// 保存接受的数据容器
	private static final int MAX_COUNT_OF_VALUES = 50;// 最多保存数据的个数
	// private
	private MyCanvas trendChartCanvas = new MyCanvas();
	// 框架起点坐标
	private final int FREAME_X = 50;// 坐标横向位置
	private final int FREAME_Y = 50;// 坐标纵向位置
	private final int FREAME_WIDTH = 600;// 横
	private final int FREAME_HEIGHT = 350;// 纵

	// 原点坐标
	private final int Origin_X = FREAME_X + 50;// 50为y坐标数值宽度
	private final int Origin_Y = FREAME_Y + FREAME_HEIGHT - 30;// 30为x坐标数字高度

	// X,Y轴终点坐标
	private final int XAxis_X = FREAME_X + FREAME_WIDTH - 30;
	private final int XAxis_Y = Origin_Y;
	private final int YAxis_X = Origin_X;
	private final int YAxis_Y = FREAME_Y + 30;

	// X轴上的时间分度值(1分度=40像素)
	private final int TIME_INTERVAL = 50;// 方格宽度
	// Y轴上值
	private final int PRESS_INTERVAL = 50;// 方格高度

	// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	private int MapValue = 0;

	public void setMapValue(int readBuffer) {
		MapValue = readBuffer;// 传入串口数据
	}
	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	public Chart_test() {
		super("前端界面显示:");
		values = Collections.synchronizedList(new ArrayList<Integer>());// 防止引起线程异常
		// 创建一个随机数线程
		new Thread(new Runnable() {
			int num = 0;

			public void run() {
				// Random rand = new Random();
				try {
					while (true) {
						num = MapValue;
						System.out.println("画图数据:" + num);
						addValue(num);
						repaint();
						Thread.sleep(100);// 传递延时

					}
				} catch (InterruptedException b) {
					b.printStackTrace();
				}
			}

		}).start();

		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setBounds(300, 200, 900, 600);
		this.add(trendChartCanvas, BorderLayout.CENTER);
		this.setVisible(true);
	}

	public void addValue(int value) {
		// 循环的使用一个接受数据的空间
		if (values.size() > MAX_COUNT_OF_VALUES) {
			values.remove(0);
		}
		values.add(value);
	}

	// 画布重绘图
	class MyCanvas extends JPanel {
		private static final long serialVersionUID = 1L;

		public void paintComponent(Graphics g) {
			Graphics2D g2D = (Graphics2D) g;
			Color c = new Color(200, 70, 0);
			g.setColor(c);
			super.paintComponent(g);
			// 绘制平滑点的曲线
			g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
			int w = XAxis_X;// 起始点
			int xDelta = w / MAX_COUNT_OF_VALUES;
			int length = values.size() - 10;
			for (int i = 0; i < length - 1; ++i) {
				/*
				 * if(values.get(i)>=160) { values.set(i,160);
				 * 
				 * } else if(values.get(i)<=50){ values.set(i,50); } if(values.get(i+1)>=160) {
				 * values.set(i+1,160);
				 * 
				 * } else if(values.get(i+1)<=50){ values.set(i+1,50); }
				 */
				// System.out.println("max:"+getMax(values));
				// System.out.println("min:"+getMin(values));
				g2D.drawLine(xDelta * (MAX_COUNT_OF_VALUES - length + i), -values.get(i) + Origin_Y,
						xDelta * (MAX_COUNT_OF_VALUES - length + i + 1), -values.get(i + 1) + Origin_Y);
			}
			// 画坐标轴
			g2D.setStroke(new BasicStroke(Float.parseFloat("2.0F")));// 轴线粗度
			// X轴以及方向箭头
			g.drawLine(Origin_X, Origin_Y, XAxis_X, XAxis_Y);// x轴线的轴线
			g.drawLine(XAxis_X, XAxis_Y, XAxis_X - 5, XAxis_Y - 5);// 上边箭头
			g.drawLine(XAxis_X, XAxis_Y, XAxis_X + 5, XAxis_Y + 5);// 下边箭头
			// Y轴以及方向箭头
			g.drawLine(Origin_X, Origin_Y, YAxis_X, YAxis_Y);
			g.drawLine(YAxis_X, YAxis_Y, YAxis_X - 5, YAxis_Y + 5);
			g.drawLine(YAxis_X, YAxis_Y, YAxis_X + 5, YAxis_Y + 5);

			// 画X轴上的时间刻度(从坐标轴原点起,每隔TIME_INTERVAL(时间分度)像素画一时间点,到X轴终点止)
			g.setColor(Color.BLUE);
			g2D.setStroke(new BasicStroke(Float.parseFloat("1.0f")));

			// X轴刻度依次变化情况
			for (int i = Origin_X, j = 0; i < XAxis_X; i += TIME_INTERVAL, j += TIME_INTERVAL) {
				g.drawString(" " + j, i - 10, Origin_Y + 20);
			}
			g.drawString("时间", XAxis_X + 5, XAxis_Y + 5);

			// 画Y轴上血压刻度(从坐标原点起,每隔10像素画一压力值,到Y轴终点止)
			for (int i = Origin_Y, j = 0; i > YAxis_Y; i -= PRESS_INTERVAL, j += TIME_INTERVAL) {
				g.drawString(j + " ", Origin_X - 30, i + 3);
			}
			g.drawString("幅度/Amplitude", YAxis_X - 5, YAxis_Y - 5);// 血压刻度小箭头值
			// 画网格线
			g.setColor(Color.BLACK);
			// 坐标内部横线
			for (int i = Origin_Y; i > YAxis_Y; i -= PRESS_INTERVAL) {
				g.drawLine(Origin_X, i, Origin_X + 10 * TIME_INTERVAL, i);
			}
			// 坐标内部竖线
			for (int i = Origin_X; i < XAxis_X; i += TIME_INTERVAL) {
				g.drawLine(i, Origin_Y, i, Origin_Y - 5 * PRESS_INTERVAL);
			}
		}
	}

	// 获取临时数据最大值
	public static int getMax(List<Integer> ins) {
		Object[] objs = ins.toArray();
		Arrays.sort(objs);
		return Integer.valueOf(String.valueOf(objs[objs.length - 1]));
	}

	// 获取临时数据最小值
	public static int getMin(List<Integer> ins) {
		Object[] objs = ins.toArray();
		Arrays.sort(objs);
		return Integer.valueOf(String.valueOf(objs[0]));
	}
	/*
	 * public static void main(String[] args) { // TODO Auto-generated method stub
	 * new Chart_test(); }
	 */

}


Similar Posts

下一篇 java基础学习

Comments