当前位置:首页 » 安卓系统 » androidserialport

androidserialport

发布时间: 2022-08-14 20:31:34

㈠ android 串口通信丢失数据原因

我现在测试也遇到这个问题,我是根据android_serialport_api里面的代码做的,就是在android端接收串口发过来的数据不完整,几乎每次都只是接收一部分的数据,另外一部分就不知道跑到哪里去,请问你这个问题你解决了吗

㈡ 怎么编译 串口android-serialport-api

说的几个问题
要了解在VC6.0必须使用XP系统,win7的安全性是太高了,部分的动态链接库的变化,导致一些程序无法运行。
在WinXP中可以看到,到底出了什么错。例如,winxp的报警,请问您的地址读取错误导致程序崩溃,缓冲区溢出,缓冲区溢出,WIN7不喜欢你的头发,这个数字显然知道,什么都不知道的报警

其次,在编译时没有任何错误,但这个语法没有任何错误,但并不意味着该程序是没有错误
例如
诠释*;
* I = 123;
上述两者之间没有任何语法错误,但是一运行就死机,表明该内存不能写入
错误的原因很明显,没有给一个指针,我被分配一个值的地址,想给一个模糊的地址写入到123,当然,一个错误
没有问题
诠释一;
诠释* I = &A;
* I = 123 / / 123被写入到介质。
串行通信无非是读取和写入文件的读取与写入功能
错误的原因是读或写功能
第二个参数是一个void指针?
或者第一个参数的串口文件指针不存在
或第三个参数是大于与所述第二参数的大小?

㈢ android serialport 为什么获取两遍

哈哈哈

㈣ android虚拟机串口通信

工具:Virtual Serial Port Driver.
用这个工具虚拟出一对串口。
下载地址

2.用串口调试助手,测试串口通信。
3.用这个命令启动虚拟机:emulator @2.2 -scale auto -qemu -serial COM3 &
说明:
2.2:是虚拟机的名称。
COM3是你要选择的串口。
ps:在cmd中使用这个命令有两种方式:1)将安卓的sdk的tools文件夹加入到path环境变量中,2)在安卓的sdk的tools文件夹下打开cmd。
4.虚拟机中测试串口通信用谷歌的一个开源项目:android_serialport_api
5.在虚拟机中运行项目。
说明:运行前要获取设备的权限
1)在cmd中用adb shell命令,进入虚拟机命令行环境。

2)打开dev文件夹:cd dev
3)获取权限:chmod 777 ttyS2

6.谷歌的开源项目不能导入进eclipse,我整理了一下,调通了。

㈤ 谁有没有Android串口的使用例子

1 首先做的是创建新的工程然后添加一下文件


3代码

好了 然后就是关于这个页面的Code了,

这是我的:

package android.serialport;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.BreakIterator;
import java.util.ServiceConfigurationError;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MyserialActivity extendsActivity
{
EditText sendedit;
EditText receiveedit;
FileInputStream mInStream;
FileOutputStream mOutStream;
SerialPort classserialport;
ReadThread mReadThread;

private class ReadThread extends Thread
{
public void run()
{
super.run();
while(!isInterrupted())
{
int size;
}
}
}


void onDataReceive(final byte[] buffer,finalint size)
{
runOnUiThread(new Runnable()
{

@Override
publicvoid run()
{
// TODO Auto-generated method stub
if(mReadThread != null)
{
receiveedit.append(newString(buffer,0,size));
}
}
});
}
@Override
protectedvoid onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_myserial);

sendedit= (EditText)findViewById(R.id.editText1);
receiveedit=(EditText)findViewById(R.id.editText2);


receiveedit.setFocusable(false);//进制输入
/*
* 打开串口
* */
finalButton openserial =(Button)findViewById(R.id.button1);
openserial.setOnClickListener(newView.OnClickListener()
{

@Override
publicvoid onClick(View arg0)
{
//TODO Auto-generated method stub
try
{
classserialport=new SerialPort(new File("/dev/ttyS2"),9600);
}catch(SecurityExceptione)
{
e.printStackTrace();
}
catch(IOExceptione)
{
e.printStackTrace();
}
mInStream=(FileInputStream) classserialport.getInputStream();
Toast.makeText(MyserialActivity.this,"串口打开成功",Toast.LENGTH_SHORT).show();
}
});
/*
* 发送数据
* */
finalButton sendButton =(Button)findViewById(R.id.button2);
sendButton.setOnClickListener(newView.OnClickListener()
{

@Override
publicvoid onClick(View arg0)
{

Stringindata;
indata=sendedit.getText().toString();
//TODO Auto-generated method stub
try
{
mOutStream=(FileOutputStream) classserialport.getOutputStream();
mOutStream.write(indata.getBytes());
mOutStream.write(' ');
}
catch(IOExceptione)
{
e.printStackTrace();
}
Toast.makeText(MyserialActivity.this,"数据发送成功",Toast.LENGTH_SHORT).show();
sendedit.setText("");
}
});
/*
* 接收数据
* */
finalButton receButton= (Button)findViewById(R.id.button3);
receButton.setOnClickListener(newView.OnClickListener()
{//inttag =0;

@Override
publicvoid onClick(View arg0)
{
// TODO Auto-generated method stub
intsize;
try
{
byte[]buffer = new byte[64];
if(mInStream== null) return;
size= mInStream.read(buffer);
if(size>0)
{
receiveedit.setText("");

}
if(size>0)
{
onDataReceive(buffer,size);
}
inttag =1;

receiveedit.setText(newString(buffer, 0, size));

}catch(IOExceptione)
{
e.printStackTrace();
return;
}
}

privateboolean isInterrupted()
{
// TODO Auto-generated methodstub
returnfalse;
}
});
/*
* 清楚接收区
* */
finalButton ClearButton = (Button)findViewById(R.id.clear);
ClearButton.setOnClickListener(newView.OnClickListener()
{

@Override
publicvoid onClick(View arg0)
{
//TODO Auto-generated method stub
receiveedit.setText("");
}
});}

@Override
publicboolean onCreateOptionsMenu(Menu menu)
{
//Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.myserial,menu);
returntrue;
}

}

好吧 你做好了。

3需要加载的文件

下面我把所需要添加的代码贴一贴

第一个是Serialport.java

/*
* Copyright 2009 Cedric Priscal
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package android.serialport;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.util.Log;

public class SerialPort {

private static final String TAG = "SerialPort";

/*
* Do not remove or rename the field mFd: it is used by native method close();
*/
private FileDescriptor mFd; //创建一个文件描述符对象 mFd
private FileInputStream mFileInputStream;
private FileOutputStream mFileOutputStream;

public SerialPort(File device, int baudrate) throws SecurityException, IOException {
/*
* 检查访问权限
* */
/* Check access permission */
if (!device.canRead() || !device.canWrite()) {//如果设备不可读或者设备不可写
try {
/* Missing read/write permission, trying to chmod the file *///没有读写权限,就尝试去挂载权限
Process su; //流程进程 su
su = Runtime.getRuntime().exec("/system/bin/su");//通过执行挂载到/system/bin/su 获得执行
String cmd = "chmod 777 " + device.getAbsolutePath() + " "
+ "exit ";
/*String cmd = "chmod 777 /dev/s3c_serial0" + " "
+ "exit ";*/
su.getOutputStream().write(cmd.getBytes());//进程。获得输出流。写(命令。获得二进制)
if ((su.waitFor() != 0) || !device.canRead()
|| !device.canWrite()) {//如果 进程等待不是0 或者 设备不能读写就
throw new SecurityException();//抛出一个权限异常
}
} catch (Exception e) {
e.printStackTrace();
throw new SecurityException();
}
}
/*
*
* */
mFd = open(device.getAbsolutePath(), baudrate);
//device.getAbsolutePath()这是要挂载的路径new File("/dev/ttyS2")
if (mFd == null) {
Log.e(TAG, "native open returns null");
throw new IOException();//输入输出异常
}
//将文件描述符 做输入输出流的参数 传递给创建的输入输出流
mFileInputStream = new FileInputStream(mFd);
mFileOutputStream = new FileOutputStream(mFd);
}

// Getters and setters
public InputStream getInputStream() {
return mFileInputStream;
}

public OutputStream getOutputStream() {
return mFileOutputStream;
}

// JNI
private native static FileDescriptor open(String path, int baudrate);
public native void close();
static {
System.loadLibrary("serial_port");
}
}

第二个是SerialPortFinder.java

/*
* Copyright 2009 Cedric Priscal
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package android.serialport;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.Iterator;
import java.util.Vector;

import android.util.Log;

public class SerialPortFinder {

/*
* 创建一个驱动程序类
* */
public class Driver {
public Driver(String name, String root) {
mDriverName = name;//String 类型的
mDeviceRoot = root;
}
private String mDriverName;
private String mDeviceRoot;
Vector<File> mDevices = null;
/*
* Vector 类在 java 中可以实现自动增长的对象数组
* 简单的使用方法如下:
vector<int> test;//建立一个vector
test.push_back(1);
test.push_back(2);//把1和2压入vector这样test[0]就是1,test[1]就是2
* */
public Vector<File> getDevices() {
if (mDevices == null) {
mDevices = new Vector<File>();
File dev = new File("/dev");
File[] files = dev.listFiles();
int i;
for (i=0; i<files.length; i++) {
if (files[i].getAbsolutePath().startsWith(mDeviceRoot)) {
Log.d(TAG, "Found new device: " + files[i]);
mDevices.add(files[i]);
}
}
}
return mDevices;
}

public String getName() {
return mDriverName;
}
}
/*
*
*
* */
private static final String TAG = "SerialPort";

private Vector<Driver> mDrivers = null;

Vector<Driver> getDrivers() throws IOException {
if (mDrivers == null) {
mDrivers = new Vector<Driver>();
LineNumberReader r = new LineNumberReader(new FileReader("/proc/tty/drivers"));
String l;
while((l = r.readLine()) != null) {
String[] w = l.split(" +");
if ((w.length == 5) && (w[4].equals("serial"))) {
Log.d(TAG, "Found new driver: " + w[1]);
mDrivers.add(new Driver(w[0], w[1]));
}
}
r.close();
}
return mDrivers;
}

public String[] getAllDevices() {
Vector<String> devices = new Vector<String>();
// Parse each driver
Iterator<Driver> itdriv;
try {
itdriv = getDrivers().iterator();
while(itdriv.hasNext()) {
Driver driver = itdriv.next();
Iterator<File> itdev = driver.getDevices().iterator();
while(itdev.hasNext()) {
String device = itdev.next().getName();
String value = String.format("%s (%s)", device, driver.getName());
devices.add(value);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return devices.toArray(new String[devices.size()]);
}

public String[] getAllDevicesPath() {
Vector<String> devices = new Vector<String>();
// Parse each driver
Iterator<Driver> itdriv;
try {
itdriv = getDrivers().iterator();
while(itdriv.hasNext()) {
Driver driver = itdriv.next();
Iterator<File> itdev = driver.getDevices().iterator();
while(itdev.hasNext()) {
String device = itdev.next().getAbsolutePath();
devices.add(device);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return devices.toArray(new String[devices.size()]);
}
}

第三个是Android.mk

#
# Copyright 2009 Cedric Priscal
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

TARGET_PLATFORM := android-3
LOCAL_MODULE := serial_port
LOCAL_SRC_FILES := SerialPort.c
LOCAL_LDLIBS := -llog

include $(BUILD_SHARED_LIBRARY)

第四个是SerialPort.c

/*
* Copyright 2009 Cedric Priscal
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#include <termios.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <jni.h>

#include "android/log.h"
static const char *TAG="serial_port";
#define LOGI(fmt, args...) __android_log_print(ANDROID_LOG_INFO, TAG, fmt, ##args)
#define LOGD(fmt, args...) __android_log_print(ANDROID_LOG_DEBUG, TAG, fmt, ##args)
#define LOGE(fmt, args...) __android_log_print(ANDROID_LOG_ERROR, TAG, fmt, ##args)

static speed_t getBaudrate(jint baudrate)
{
switch(baudrate) {
case 0: return B0;
case 50: return B50;
case 75: return B75;
case 110: return B110;
case 134: return B134;
case 150: return B150;
case 200: return B200;
case 300: return B300;
case 600: return B600;
case 1200: return B1200;
case 1800: return B1800;
case 2400: return B2400;
case 4800: return B4800;
case 9600: return B9600;
case 19200: return B19200;
case 38400: return B38400;
case 57600: return B57600;
case 115200: return B115200;
case 230400: return B230400;
case 460800: return B460800;
case 500000: return B500000;
case 576000: return B576000;
case 921600: return B921600;
case 1000000: return B1000000;
case 1152000: return B1152000;
case 1500000: return B1500000;
case 2000000: return B2000000;
case 2500000: return B2500000;
case 3000000: return B3000000;
case 3500000: return B3500000;
case 4000000: return B4000000;
default: return -1;
}
}

/*
* Class: cedric_serial_SerialPort
* Method: open
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT jobject JNICALL Java_android_serialport_SerialPort_open
(JNIEnv *env, jobject thiz, jstring path, jint baudrate)
{
int fd;
speed_t speed;
jobject mFileDescriptor;

/* Check arguments */
{
speed = getBaudrate(baudrate);
if (speed == -1) {
/* TODO: throw an exception */
LOGE("Invalid baudrate");
return NULL;
}
}

/* Opening device */
{
jboolean is;
const char *path_utf = (*env)->GetStringUTFChars(env, path, &is);
LOGD("Opening serial port %s", path_utf);
fd = open(path_utf, O_RDWR | O_DIRECT | O_SYNC);
LOGD("open() fd = %d", fd);
(*env)->ReleaseStringUTFChars(env, path, path_utf);
if (fd == -1)
{
/* Throw an exception */
LOGE("Cannot open port");
/* TODO: throw an exception */
return NULL;
}
}

/* Configure device */
{
struct termios cfg;
LOGD("Configuring serial port");
if (tcgetattr(fd, &cfg))
{
LOGE("tcgetattr() failed");
close(fd);
/* TODO: throw an exception */
return NULL;
}

cfmakeraw(&cfg);
cfsetispeed(&cfg, speed);
cfsetospeed(&cfg, speed);

if (tcsetattr(fd, TCSANOW, &cfg))
{
LOGE("tcsetattr() failed");
close(fd);
/* TODO: throw an exception */
return NULL;
}
}

/* Create a corresponding file descriptor */
{
jclass cFileDescriptor = (*env)->FindClass(env, "java/io/FileDescriptor");
jmethodID iFileDescriptor = (*env)->GetMethodID(env, cFileDescriptor, "<init>", "()V");
jfieldID descriptorID = (*env)->GetFieldID(env, cFileDescriptor, "descriptor", "I");
mFileDescriptor = (*env)->NewObject(env, cFileDescriptor, iFileDescriptor);
(*env)->SetIntField(env, mFileDescriptor, descriptorID, (jint)fd);
}

return mFileDescriptor;
}

/*
* Class: cedric_serial_SerialPort
* Method: close
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_android_serialport_SerialPort_close
(JNIEnv *env, jobject thiz)
{
jclass SerialPortClass = (*env)->GetObjectClass(env, thiz);
jclass FileDescriptorClass = (*env)->FindClass(env, "java/io/FileDescriptor");

jfieldID mFdID = (*env)->GetFieldID(env, SerialPortClass, "mFd", "Ljava/io/FileDescriptor;");
jfieldID descriptorID = (*env)->GetFieldID(env, FileDescriptorClass, "descriptor", "I");

jobject mFd = (*env)->GetObjectField(env, thiz, mFdID);
jint descriptor = (*env)->GetIntField(env, mFd, descriptorID);

LOGD("close(fd = %d)", descriptor);
close(descriptor);
}

㈥ android串口通信如何发送16进制给给下位机

已解决,发送串口帧数据时,对于16进制数据定义,直接用byte[]数组就行了,不需要用Array.fill函数;

㈦ 如何开放android的串口权限

要调用串口,肯定是要用到JNI的,而且要有打开对应串口设备的权限
至于是不是通过USB转的,没啥关系,因为USB转串口的驱动已经把USB的特征封装了,就当它是一个纯串口操作就行
android-serialport-api也是用的JNI,要想知道能不能用,装它的DEMO代码试试就知道了
不然重新写一个JNI的库,用android-serialport-api的也行,不然网上也好多现成的代码,基本不用重写

㈧ android 应用程序通过什么方法与串口进行通信,怎么像串口发送数据帧

ModBus 可分为两种传输模式: ASCII 模式和 RTU 模式。使用何种模式由用户自行选 择,包括串口通信参数(波特率、校验方式等)。在配置每个控制器的时候,同一个 Mod B us 网络上的所有设备都必须选择相同的传输模式和串口参数。 1 ASCII 模式 ...

㈨ android如何读取串口数据

楼主问题解决了没?我用串口调试助手调试,安卓端能发送数据到pc端接收,但反过来pc端发数据过来安卓无法接收,求大神指导啊

㈩ android串口消息

android串口消息连接的方法为:
1.模拟器可以使用PC的串口。
启动模拟器并加载PC串口 命令如下。
运行 emulator @模拟器名称 -qmu -serial COM1。
2.查看串口是否被加载。
启动后使用 adb shell 命令打开命令行
cd dev 查看会发现ttyS0 ttyS1 ttyS2,其他ttyS2 就是我们加载上来的串口COM1
3.修改权限
chmod 777 ttyS2
现在我们可以开发串口程序了。
4.串口程序实例
下载libserial_port.so ,放入libs/armeabi 目录,可以自己创建此目录
libserial_port.so 下载地址:
http://code.google.com/p/android-serialport-api/
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.util.Log;

public class SerialPort {

private static final String TAG = "SerialPort";

private FileDescriptor mFd;
private FileInputStream mFileInputStream;
private FileOutputStream mFileOutputStream;

public SerialPort(File device, int baudrate) throws SecurityException, IOException {

if (!device.canRead() || !device.canWrite()) {
try {
Process su;
su = Runtime.getRuntime().exec("/system/bin/su");
String cmd = "chmod 666 " + device.getAbsolutePath() + "n"
+ "exitn";
su.getOutputStream().write(cmd.getBytes());
if ((su.waitFor() != 0) || !device.canRead()
|| !device.canWrite()) {
throw new SecurityException();
}
} catch (Exception e) {
e.printStackTrace();
throw new SecurityException();
}
}

mFd = open(device.getAbsolutePath(), baudrate);
if (mFd == null) {
Log.e(TAG, "native open returns null");
throw new IOException();
}
mFileInputStream = new FileInputStream(mFd);
mFileOutputStream = new FileOutputStream(mFd);
}

public InputStream getInputStream() {
return mFileInputStream;
}

public OutputStream getOutputStream() {
return mFileOutputStream;
}

//JNI
private native static FileDescriptor open(String path, int baudrate);
public native void close();
static {
System.loadLibrary("serial_port");
}
}

####################################

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class PrintClass {

//输入流
private static InputStream in;
//输出流
private static OutputStream out;

private static final String PORT = "/dev/ttyS2";//串口

private SerialPort serialPort;

private void Connect()
{
try {
serialPort = new SerialPort(new File(PORT), 38400);

in = serialPort.getInputStream();
out = serialPort.getOutputStream();

} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public void CloseSerialPort()
{
try {
out.close();
in.close();
serialPort.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}

热点内容
诺基亚密码忘了打什么电话 发布:2024-09-17 03:27:09 浏览:555
树深度优先算法 发布:2024-09-17 03:26:58 浏览:472
跳转页源码 发布:2024-09-17 03:13:05 浏览:543
html文件上传表单 发布:2024-09-17 03:08:02 浏览:785
聊天软件编程 发布:2024-09-17 03:00:07 浏览:726
linuxoracle安装路径 发布:2024-09-17 01:57:29 浏览:688
两个安卓手机照片怎么同步 发布:2024-09-17 01:51:53 浏览:207
cf编译后没有黑框跳出来 发布:2024-09-17 01:46:54 浏览:249
安卓怎么禁用应用读取列表 发布:2024-09-17 01:46:45 浏览:524
win10设密码在哪里 发布:2024-09-17 01:33:32 浏览:662