我正在尝试通过Arduino Uno和pc java来控制一个小的直流电机。此java应用程序是服务器应用程序,使用socket与android应用程序连接。并且它可以在java的单个命令上工作。但不能连续按下。当我连续按下按钮并停止按下up时,我想要旋转电机。请帮帮我。
以下是android代码。/continuously press/
class RepetitiveUpdater implements Runnable {
@Override
public void run() {
if (autoIncrement) {
increment();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
repeatUpdateHandler.postDelayed(new RepetitiveUpdater(), REPEAT_DELAY);
} else if (autoDecrement) {
decrement();
repeatUpdateHandler.postDelayed(new RepetitiveUpdater(), REPEAT_DELAY);
}
}
}
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
increment();
}
});
btn.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
autoIncrement = true;
repeatUpdateHandler.post(new RepetitiveUpdater());
return false;
}
});
btn1.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
autoDecrement = true;
repeatUpdateHandler.post(new RepetitiveUpdater());
return false;
}
});
这是java服务器。
private void sendMsgToPort(int k) {
try {
String s = String.valueOf(k);
char buf2[] = s.toCharArray();
serialPort.writeByte((byte) buf2[0]);
} catch (SerialPortException ex) {
System.out.println(ex);
}
}
// ........
while (true) {
try {
clientSocket = serverSocket.accept(); // accept the client connection
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); // get the client message
message = bufferedReader.read();
sendMsgToPort(message);
System.out.println("m=:" + message);
// System.out.println("Serial : "+serialPort.readString());
//inputStreamReader.close();
// clientSocket.close();
//System.out.println(serialPort.readBytes());
//Thread.sleep(100);
} catch (IOException ex) {
// status.setText("Error: " + ex);
System.out.println("Problem in message reading");
}
}
下面是ardiuno示例代码:
int val = 0;
int led = 8;
void setup()
{
Serial.begin(9600);
pinMode(led, OUTPUT);
}
void loop()
{
delay(100);
}
void serialEvent() // To check if there is any data on the Serial line
{
if (Serial.available())
{
val = Serial.parseInt();
if(val == 1) //Switch on the LED, if the received value is 1.
{
digitalWrite(led, HIGH);
}
}
}
`
发布于 2017-01-11 23:10:56
您的Java服务器程序中存在一个问题:
clientSocket = serverSocket.accept();
您接受一个新的连接,读取/处理一条消息,然后呢?客户端套接字只是超出了作用域。连接处于打开状态,您的代码将再次等待新的连接。
搜索"Java多线程服务器“示例,这真的很简单。在接受之后,让每个连接在一个专用线程中完全处理,这样您就可以同时等待另一个连接,并在已建立的连接上处理更长的对话框。
https://stackoverflow.com/questions/41572594
复制相似问题