Im trying to make connection between my computer and arduino uno using Java Simple Serial Connector. Im trying to do it using code listed below. Somehow its not working ( the led diode connected to pin 7 of arduino is not turning on while running my programm, but when im using serial monitor of artuino software it does. ). Does anyone know why?
Java project code :
import jssc.SerialPort;
import jssc.SerialPortException;
public class Main {
public static void main(String[] args) {
//In the constructor pass the name of the port with which we work
SerialPort serialPort = new SerialPort("COM3");
try {
//Open port
serialPort.openPort();
//We expose the settings. You can also use this line - serialPort.setParams(9600, 8, 1, 0);
serialPort.setParams(SerialPort.BAUDRATE_9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
//Writes data to port
serialPort.writeBytes("Test".getBytes());
//Closing the port
serialPort.closePort();
}
catch (SerialPortException ex) {
System.out.println(ex);
}
}
}`
Arduino code:
void setup() {
Serial.begin(9600); //Ustawienie prędkości transmisji
pinMode(7, OUTPUT);
digitalWrite(7, LOW);
}
void loop() {
if( Serial.available() > 0){
digitalWrite(7, HIGH);
}
}
I think, your Arduinocode is wrong.
I do it like this.
https://www.arduino.cc/en/Serial/Write
Serial.write(val)
Serial.write(str)
Serial.write(buf, len)
val: a value to send as a single byte
str: a string to send as a series of bytes
buf: an array to send as a series of bytes
len: the length of the buffer
Related
I made a python server and a java client. My problem is simple:
The server receives the message from client, but the client doesn't get the reply.
Java Client:
package fgd;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
public class fdassd {
public static void main(String[] args){
new Thread(){
public void run(){
while (true)
{
try {Socket socke=new Socket("censored",1977);
DataOutputStream dout=new DataOutputStream(socke.getOutputStream());
DataInputStream din = new DataInputStream(socke.getInputStream());
dout.writeUTF("Heey");
dout.flush();
String str = din.readUTF();
System.out.println(str);
dout.close();
socke.close();
}catch(Exception e){
e.printStackTrace();
}
try {
Thread.sleep(17000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
}
}
Python Server:
hosto = '0.0.0.0'
porto = 1979
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created!'
try:
soc.bind((hosto, porto))
except socket.error as e:
print(e)
sys.exit()
print 'Socket bind complete'
soc.settimeout(30)
soc.listen(10)
print 'Listening...'
timeout = 8
timeout_start = time.time()
while time.time() < timeout_start + timeout:
try:
conn, addr = soc.accept()
if addr[0] != opip:
conn.shutdown(socket.SHUT_RDWR)
conn.close()
else:
msg = conn.recv(1024)
print ('--------------------------------------')
print (msg)
conn.send((playername).encode('UTF-8'))
print ('Success! The following command has been sent to: ' + opip + ':' + playername )
print ('--------------------------------------')
soc.close()
break
except socket.timeout as e:
print(e,': Server not online or wrong ip')
soc.close()
break
else:
I've seen a very similar question where the answer was to add to lines before conn.send (Link: Socket Java client - Python Server).
But I can't use the solution in that question, because
conn.send(len(message_to_send).to_bytes(2, byteorder='big'))
doesn't seem to work in python 2.x .That means I need another solution to send the message with UTF-8 but I can't figure out what to do.
Regards
Add the following line, before you send the playername. This should work in both python2 and 3:
conn.send(struct.pack(">H", len(playername)))
This line will prefix the length of the player name to the message, as is required by the java DataInputStream#readUTF method. It's encoded as a two-byte integer, hence the 'H' in the struct.pack call.
You will also need an import struct statement.
See Python 2,3 Convert Integer to "bytes" Cleanly for more information.
I'm trying to have an Arduino UNO send values to a IOIO board (https://github.com/ytai/ioio/wiki/UART) over UART. As someone turns a rotary encoder, I want it to send a 0 for CW, 1 for CCW, and 2 for a press. Everything checks out in the Serial Monitor from the Arduino, but I don't know how to read the values and parse them on the Java-end correctly. It all comes through as seemingly random numbers, sometimes occasionally the correct number is there.
I've tried both of these methods on the Arduino side:
Serial.write(1);
byte data[] = {1};
Serial.write(data, 1);
Also Serial.write automatically writes to pin 1, so theres no need to create a SoftwareSerial object.
When reading this on the Java side, I just get mostly 255, occasionally the correct number, and occasionally a random number in between 0 and 255:
#Override
public void connect() throws ConnectionLostException {
try{
// rx pin = 6
mUart = ioio_.openUart(RX_PIN, IOIO.INVALID_PIN, 9600, Parity.NONE, StopBits.ONE);
mInput = mUart.getInputStream();
}
catch(ConnectionLostException e){
Log.e(TAG, "connection lost:" + e.getMessage());
ioio_.disconnect();
throw e;
}
}
#Override
public void loop(int loopCount) throws ConnectionLostException {
try{
byte[] response = new byte[1];
int read = mInput.read();
}catch(IOException e){
Log.d(TAG, "error: " + e.getMessage());
}
}
I've also tried using BufferedReaders, while passing Strings through Serial.println, but a lot of crazy characters were getting output from the Java side (tried encoding in both UTF-8 and ASCII).
Baud rates are matched up at 9600, and I'm on a 5v RX pin on the IOIO, and that pin is connected to the TX pin (pin 1) on the Arduino Uno.
Does anyone point to a simple way of transmitting & receiving an integer?
So I'm trying to communicate via client/server using sockets between a raspberry pi and a laptop. I've been able to send basic strings over using a simple python script on my pi to get the basic idea of how it worked. Now I got a little more advanced and started using OpenCV along with a usb camera to make a little security system that detects motion in the frame of the camera. I have the python script with the security system connect with the server and it is supposed to print out "Occupied" or "Unoccupied" in the console on my laptop in real time (eventually supposed to open a pop-up menu alerting that motion is detected) but it only prints out a long huge string of either "Occupied" or "Unoccupied" once I close the connection with my Pi. Why isn't it printing out in real time? Here is the java code on my laptop, unforunately my Pi is in school at the moment and I can't access the python code but I will post it tomorrow.
public class PyComms {
public static void main(String[] args) {
try{
ServerSocket server = new ServerSocket(4444);
System.out.println("Waiting for client on port 4444");
while(true){
Socket connected = server.accept();
System.out.println("CONNECTED WITH CLIENT");
BufferedReader inFromPi = new BufferedReader(new InputStreamReader(connected.getInputStream()));
while(true){
String fromclient = inFromPi.readLine();
if(fromclient.equalsIgnoreCase("Occupied")){
System.out.println("Client responded with "+fromclient + "\n");
}
else{
System.out.println("Client responded with "+fromclient + "\n");
connected.close();
}
}
}
}
catch(Exception e){
System.out.println(e);
}
}
}
The answer was exactly what #jtahlborn said. All I had to do was include a new line after each message was sent in the python code. I achieved this by doing something similar to client_socket.send(text+'\n')
I'm trying to get some values from rs232 (card reader Roger prt66lt) with a java simple serial connetor (jssc) but it look like i dont get any events started. I'm using the example code. The card reader is set to send card number when he reads it. But i dont get any event started coz i dont see event that System.out. I'm including jssc.jar (from 2.5.0 version) and its connecting to divice. Is this version of jssc doesnt need any .dll ? I think its included in it ? The similar code to this one but with RXTX library works fine but i need to include attahed dll library.
Card reader send me HEX value: 02, 10 chars DATA, 0D, 0A, 03
Code:
import jssc.SerialPort;
import jssc.SerialPortEvent;
import jssc.SerialPortEventListener;
import jssc.SerialPortException;
public class Main {
static SerialPort serialPort;
public static void main(String[] args) {
serialPort = new SerialPort("COM4");
try {
serialPort.openPort();//Open port
serialPort.setParams(9600, 8, 1, 0);//Set params
int mask = SerialPort.MASK_RXCHAR + SerialPort.MASK_CTS + SerialPort.MASK_DSR;//Prepare mask
serialPort.setEventsMask(mask);//Set mask
serialPort.addEventListener(new SerialPortReader());//Add SerialPortEventListener
}
catch (SerialPortException ex) {
System.out.println(ex);
}
}
static class SerialPortReader implements SerialPortEventListener {
public void serialEvent(SerialPortEvent event) {
System.out.println("Event started");
if(event.isRXCHAR()){//If data is available
if(event.getEventValue() == 10){//Check bytes count in the input buffer
//Read data, if 10 bytes available
try {
byte buffer[] = serialPort.readBytes(10);
}
catch (SerialPortException ex) {
System.out.println(ex);
}
}
}
else if(event.isCTS()){//If CTS line has changed state
if(event.getEventValue() == 1){//If line is ON
System.out.println("CTS - ON");
}
else {
System.out.println("CTS - OFF");
}
}
else if(event.isDSR()){///If DSR line has changed state
if(event.getEventValue() == 1){//If line is ON
System.out.println("DSR - ON");
}
else {
System.out.println("DSR - OFF");
}
}
}
}
}
The problem was that the default setting of RTS and DTR line is High so i need to use another setParams method and set the RTS line to false as needed by device.
Solution:
serialPort.setParams(9600, 8, 1, 0, false, true);
I have modified the example shown on https://code.google.com/p/java-simple-serial-connector/wiki/jSSC_examples to show read/write from java program. I can run the program, however the data I send using serialPort.writeString("HelloWorld"); does not seem to be read in the SerialPortReader event class. Could any one please point what the issue is ?
public class SerialReaderWriter {
static SerialPort serialPort;
public static void main(String[] args) {
serialPort = new SerialPort("COM1");
try {
serialPort.openPort();
serialPort.setParams(9600, 8, 1, 0);
//Preparing a mask. In a mask, we need to specify the types of events that we want to track.
//Well, for example, we need to know what came some data, thus in the mask must have the
//following value: MASK_RXCHAR. If we, for example, still need to know about changes in states
//of lines CTS and DSR, the mask has to look like this: SerialPort.MASK_RXCHAR + SerialPort.MASK_CTS + SerialPort.MASK_DSR
int mask = SerialPort.MASK_RXCHAR;
//Set the prepared mask
serialPort.setEventsMask(mask);
//Add an interface through which we will receive information about events
serialPort.addEventListener(new SerialPortReader());
serialPort.writeString("HelloWorld");
}
catch (SerialPortException ex) {
System.out.println(ex);
}
}
static class SerialPortReader implements SerialPortEventListener {
public void serialEvent(SerialPortEvent event) {
//Object type SerialPortEvent carries information about which event occurred and a value.
//For example, if the data came a method event.getEventValue() returns us the number of bytes in the input buffer.
System.out.println(event.getEventType());
if(event.isRXCHAR()){
if(event.getEventValue() == 10){
try {
String data= serialPort.readString();
System.out.println(data);
}
catch (SerialPortException ex) {
System.out.println(ex);
}
}
}
//If the CTS line status has changed, then the method event.getEventValue() returns 1 if the line is ON and 0 if it is OFF.
else if(event.isCTS()){
if(event.getEventValue() == 1){
System.out.println("CTS - ON");
}
else {
System.out.println("CTS - OFF");
}
}
else if(event.isDSR()){
if(event.getEventValue() == 1){
System.out.println("DSR - ON");
}
else {
System.out.println("DSR - OFF");
}
}
}
}
}
You can't read data from the same port where you write(COM1 here). I have followed the below steps for reading and writing using JSSC.
Fake your serial port with SerialPortMonitor.
Send data from COM2 from the SerialPortMonitor device installed.
Mode->Spy would show your written string "HelloWorld" and received String "OK"
Make the below modifications and check your code:
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN |
SerialPort.FLOWCONTROL_RTSCTS_OUT);
serialPort.writeBytes("HelloWorld");//Write data to port
PortReader portReader=new PortReader(serialPort)
serialPort.addEventListener(portReader, SerialPort.MASK_RXCHAR);
int[][] eventArray=serialPort.waitEvents()
for (int i = 0; i < eventArray.length; i++) {
if ((eventArray[i][0] > 0) ) {
serialPort.eventListener.serialEvent(new SerialPortEvent("COM1", eventArray[i][0], eventArray[i][1])); // wait for the listener event to complete
}
}
The port reader class: (You were missing the Override annotation and passing in the serial port)
public class PortReader implements SerialPortEventListener{
SerialPort serialPort
public PortReader(){}
public PortReader(SerialPort serialPort){this.serialPort=serialPort}
#Override
public void serialEvent(SerialPortEvent event) {
if(event.isRXCHAR() && event.getEventValue() > 0) {
try {
String receivedData = this.serialPort.readString(event.getEventValue());
System.out.println("Received response: " + receivedData);
this.serialPort.closePort();//Close serial port
}
catch (SerialPortException ex) {
System.out.println("Error in receiving string from COM-port: " + ex);
this.serialPort.closePort();//Close serial port
}
}
}
}
The command
serialPort.writeString("HelloWorld");
sends the string
HelloWorld
from COM1. The SerialPortReader class that you are implementing causes COM1 to listen for the event type isRXCHAR (AKA when COM1 receives a char).
Do you have a serial cable connected to the serial port?
Unless you cross the RX and TX pins of COM1 or have a separate COM port (whose TX and RX is connected to COM1's RX and TX pins respectively), the SerialPortReader will never be activated.
if your device doesn't require RTS/CTS flow control
or you dont have a fully connected serial cable
( only RX, TX, GND)
you should switch off the data terminal ready (dtr)
signal for the serial communication
add this
serialPort.setRTS(false);
serialPort.setDTR(false);
after
serialPort.addEventListener(new SerialPortReader());