我试图用PC java通过Arduino Uno控制小型直流电机。这个java应用程序是服务器应用程序,并使用socket与android app连接。它适用于java的单个命令。但是没有不断努力。当我连续按下按钮并停止按下时,我想要旋转电机。请帮我。
这是android代码。 /持续按/
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);
}
}
}
`
答案 0 :(得分:1)
Java服务器程序存在一个问题:
clientSocket = serverSocket.accept();
您接受新连接,读取/处理一条消息,然后? 那个客户端套接字超出了范围。连接刚刚打开,您的代码再次等待新连接。
搜索“Java多线程服务器”示例,这非常简单。接受后,在专用线程中完全处理每个连接,这样您就可以同时等待另一个连接并在已建立的连接上处理更长的对话。