Show Posts
Pages: [1]
1  Using Arduino / Programming Questions / Re: Serial Question [SOLVED] on: February 25, 2011, 07:08:05 pm
Alright I've been having a hell of a time with this. But I finally have it working. Here is the finished class that properly splits the data apart. I would appreciate any constructive criticism as well if anyone has any ideas on how to simplify or improve upon it.

Code:
public class ArduinoConnection implements SerialPortEventListener {
SerialPort serialPort;
        /** The port we're normally going to use. */
private static final String PORT_NAMES[] = {
"/dev/tty.usbserial-A9007UX1", // Mac OS X
"/dev/ttyUSB0", // Linux
"COM3", // Windows
};
/** the maximum number of previous datapoints to store in memory */
private static final int MAX_DATAPOINTS = 500;
/** The delimiter used between milliseconds and units */
private static final String SERIAL_DELIMITER = ":";
/** Buffered input stream from the port */
private InputStream input;
/** The output stream to the port */
//private OutputStream output;
/** Milliseconds to block while waiting for port open */
private static final int TIME_OUT = 2000;
/** Default bits per second for COM port. */
private static final int DATA_RATE = 9600;
/** Reference to main window's serial data display **/
private JTextArea ta_dataText;

/** Array to temporarily hold incoming serial data **/
private byte[] b_tempData;
/** current position of data being read into b_tempData **/
private int i_tempDataPos;

/** Array to hold data points **/
private String[] s_dataStore;
/** Temporarily hold String Array data for splitting string **/
private String[] s_temp;
/** stores the current data point position in the array **/
private int i_dataPos;
/** stores the last read data point array position **/
private int i_lastRead;

public ArduinoConnection(JTextArea ta) {
ta_dataText = ta;

b_tempData = new byte[50];
i_tempDataPos = 0;

//initialize position and array size for data points
s_dataStore = new String[MAX_DATAPOINTS];
i_dataPos = 0;
i_lastRead = 0;
}

public void open() {
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

// iterate through, looking for the port
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
for (String portName : PORT_NAMES) {
if (currPortId.getName().equals(portName)) {
portId = currPortId;
break;
}
}
}

if (portId == null) {
System.out.println("Could not find COM port.");
return;
}

try {
// open serial port, and use class name for the appName.
serialPort = (SerialPort) portId.open(this.getClass().getName(),
TIME_OUT);

// set port parameters
serialPort.setSerialPortParams(DATA_RATE,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);

// open the streams
input = serialPort.getInputStream();
//output = serialPort.getOutputStream();

// add event listeners
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);

System.out.println("ArduinoConnection | Connected to Serial");
} catch (Exception e) {
System.err.println(e.toString());
}
}

/**
* This should be called when you stop using the port.
* This will prevent port locking on platforms like Linux.
*/
public synchronized void close() {
if (serialPort != null) {
serialPort.removeEventListener();
serialPort.close();
System.out.println("ArduinoConnection | Disconnected from Serial");
}
}

/**
* Handle an event on the serial port. Read the data and store it.
*/
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
int available = input.available();
final byte chunk[] = new byte[available];
int numRead = input.read(chunk, 0, available);

//copy this chunk onto the end of temp data store
System.arraycopy(chunk, 0, this.b_tempData, this.i_tempDataPos, numRead);
//move temp data position
this.i_tempDataPos += numRead;

String currentData = new String(b_tempData);
//If end of line has been reached save this data point and reset to read next point
if(currentData.contains("\r\n")) {
s_temp = currentData.split("\r\n");

//store data
this.s_dataStore[this.i_dataPos] = s_temp[0];
System.out.println("Data Point Stored = " + this.s_dataStore[this.i_dataPos]);

//increment data point
this.i_dataPos++;

//shift any characters after the \r\n in tempData to the beginning and set new position
if(s_temp.length>1) {
//remove any whitespace before checking length of overflow chars
s_temp[1] = s_temp[1].trim();
if(s_temp[1].length()>0) {
for(int x = 0; x< s_temp[1].length(); x++) {
this.b_tempData[x] = (byte)(s_temp[1].charAt(x));
}
//set buffer position
this.i_tempDataPos = s_temp[1].length();
} else {
//reset buffer data
this.resetBuffer();
}
} else {
//reset buffer
this.resetBuffer();
}
}

//avoid gui synchronization issues on the data area update
try {
javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
//Append data to textarea on main app window
ta_dataText.append(new String(chunk)+"|");
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
System.err.println("Err:"+e.toString());
}
}
}

/** reset the b_tempData buffer array **/
private void resetBuffer() {
this.i_tempDataPos = 0;
this.b_tempData = new byte[MAX_DATAPOINTS];
}
2  Using Arduino / Programming Questions / Re: Serial Question on: February 16, 2011, 03:30:01 pm
Alright that makes sense and I just tested that.

I changed the Arduino code to this:
Code:
Serial.println("1");
 Serial.println("2");
 Serial.println("3");
 Serial.println("4");
 Serial.println("5");
 Serial.println("6");
 Serial.println("7");
 Serial.println("8");
 Serial.println("9");
 Serial.println("10");
gives me this:
Code:
SerialEvent - Read : 1
SerialEvent - Read :
2
3
4
5
6
7

SerialEvent - Read : 8
9
10
or this (randomly switches between the two, and that timing would explain it, sometimes it processes a little bit quicker
Code:
vSerialEvent - Read : 1
SerialEvent - Read :
2
3
4
5
6
7
8
SerialEvent - Read :
9
10

if I had more "1"s to the first Serial.println("11111"); it moves that middle SerialEvent - Read between 5 and 6. So I guess it takes longer with the first character because it is sending additional serial information on the first read? and then it can only read so many characters before triggering additional serial events to read in the rest.

So I'm thinking I need to send an indicator in my Arduino loop that indicates the end of a transaction after all values are sent (perhaps just a character I don't use, since I'm only sending int values anyway). Would this be the best way to go about this?

3  Using Arduino / Programming Questions / Re: Serial Question on: February 15, 2011, 05:03:37 pm
Still trying to figure out what's going on.

If all I send from the arduino Serial is
Code:
Serial.println("Testing");

What I get in my SerialEvent function is
Code:
SerialEvent - Read : T
SerialEvent - Read : esting

I haven't worked with Serial much before so I think I may just be misunderstanding something here. Is there a reason it breaks off the first character?
4  Using Arduino / Programming Questions / Serial Question [SOLVED] on: February 13, 2011, 09:30:36 am
Alright, so I'm working with reading and graphing serial data from the arduino. Everything looks right and I have been able to get the data and graph it. I was appending the serial data to a textarea and then using a Scanner object to break it apart for graphing with JFreeChart.

Here is a video of that



The problem is that now I'm trying to store the data in an array as it comes in rather than just appending it to a textarea. and it seems like the arduino is sending the serial data in 2 segments for a single Serial.println. The line being sent is
Code:
Serial.println(String(ms)+DELIMITER+String(pot));

Serial Event Java Code
Code:
/**
* Handle an event on the serial port. Read the data and store it.
*/
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
int available = input.available();
final byte chunk[] = new byte[available];
input.read(chunk, 0, available);
System.out.println("SerialEvent - Read : "+new String(chunk));
//avoid gui synchronization issues on the data area update
try {
javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
//Append data to textarea on main app window
ta_dataText.append(new String(chunk)+"|");

//increment position and store data point in array
i_pos++;
s_dataStore[i_pos] = new String(chunk);
//cycle position for next time if maximum data point stores has been met
if(i_pos == MAX_DATAPOINTS)
i_pos=0;
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
System.err.println(e.toString());
}
}
}

Console
Code:
ArduinoConnection | Connected to Serial
SerialEvent - Read : 7
SerialEvent - Read : 119:174

SerialEvent - Read : 7
SerialEvent - Read : 628:174

SerialEvent - Read : 8
SerialEvent - Read : 137:174

...

I just noticed that if I add an additional println
Code:
Serial.println(String(ms)+DELIMITER+String(pot));
 Serial.println("Testing");
it doesn't act like it's really detecting 2 serial events since you only see "Testing" after the data values, not in the middle.
Code:
ArduinoConnection | Connected to Serial
SerialEvent - Read : 2
SerialEvent - Read : 068:505
Testing

SerialEvent - Read : 2
SerialEvent - Read : 586:506
Testing

SerialEvent - Read : 3
SerialEvent - Read : 104:505
Testing

...
I have also tried just  sending
Code:
Serial.println(String(ms));
or
Code:
Serial.println(String(pot));
and these values get split up as well - (first char)(the rest), but the  String I sent directly (Testing) is not getting divided.
5  Using Arduino / Installation & Troubleshooting / Re: Arduino Serial Monitor (Ubuntu 10.04 64bit) on: February 06, 2011, 12:55:24 am
Alright, I upgraded my kernel to 2.6.32-28 and was still getting the same crash.

I found and replaced the conflicting RXTX files with the 2.2pre2 version ones and now it is working. Thanks for the help.
6  Using Arduino / Installation & Troubleshooting / Re: Arduino Serial Monitor (Ubuntu 10.04 64bit) on: February 04, 2011, 06:54:11 pm
I'm trying to search for the old library files like so:

Code:
find /. -readable -name *RXTX*
find /. -readable -name *rxtx*

But the only results are in my arduino workspace directory where I downloaded the rxtx files.

Does anyone else know where these files are hiding? or why it's still showing the old native versions when I can't even find them on the system?
7  Using Arduino / Installation & Troubleshooting / Re: Arduino Serial Monitor (Ubuntu 10.04 64bit) on: February 01, 2011, 02:04:32 pm
@mrtaylor - I am running Linux 2.6.32-24-generic x86_64

@mellis - I tried updating to the latest version multiple times but can't seem to update my native lib version. Does this just mean there is a RxTx jar on my system I need to replace with the latest version? I thought I had moved all the RxTx files to the necessary locations, but I guess not?
8  Using Arduino / Installation & Troubleshooting / Arduino Serial Monitor (Ubuntu 10.04 64bit) [SOLVED] on: January 29, 2011, 03:15:08 pm
I am still having trouble reading serial output from the Arduino. I am able to do it via the linux terminal but it crashes the Arduino IDE when I open the monitor. I also get the same error when I try and use the RxTx library to read serial with java through Eclipse.

If I run the Arduino IDE as root it results in the same crash as well.

The Arduino monitor actually worked when I first installed it up until I ran this command:
Code:
stty -F /dev/ttyUSB0 cs8 9600 ignbrk -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts
which now allows me to use the command:
Code:
tail -f /dev/ttyUSB0
to read the serial output to the terminal

Here is the original post with all the details: http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1295756150

9  Forum 2005-2010 (read only) / Troubleshooting / Re: Arduino Serial Monitor (Ubuntu 10.04 64bit) on: January 23, 2011, 01:13:46 pm
no matter how fast I disconnect-reconnect it just reattaches to ttyUSB0
Code:
[ 2412.040322] ftdi_sio 7-1:1.0: device disconnected
[ 2413.070028] usb 7-1: new full speed USB device using uhci_hcd and address 9
[ 2413.276512] usb 7-1: configuration #1 chosen from 1 choice
[ 2413.284433] ftdi_sio 7-1:1.0: FTDI USB Serial Device converter detected
[ 2413.284464] usb 7-1: Detected FT232RL
[ 2413.284467] usb 7-1: Number of endpoints 2
[ 2413.284470] usb 7-1: Endpoint 1 MaxPacketSize 64
[ 2413.284472] usb 7-1: Endpoint 2 MaxPacketSize 64
[ 2413.284474] usb 7-1: Setting MaxPacketSize 64
[ 2413.286120] usb 7-1: FTDI USB Serial Device converter now attached to ttyUSB0
10  Forum 2005-2010 (read only) / Troubleshooting / Re: Arduino Serial Monitor (Ubuntu 10.04 64bit) on: January 23, 2011, 12:37:05 pm
My Arduino always connects to /dev/ttyUSB0

Here is what I get:
Code:
corbin@skillTop:~$ stty -F /dev/ttyUSB0 -a
speed 57600 baud; rows 0; columns 0; line = 0;
intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^A; eol = <undef>; eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S; susp = ^Z;
rprnt = ^R; werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 0;
-parenb -parodd cs8 hupcl -cstopb cread clocal -crtscts
-ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr -icrnl -ixon -ixoff -iuclc -ixany -imaxbel -iutf8
-opost -olcuc -ocrnl -onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
isig -icanon iexten -echo -echoe echok -echonl -noflsh -xcase -tostop -echoprt echoctl echoke

could the 57600 baud be what is throwing me off, since in the code I am connected to serial at 9600?
11  Forum 2005-2010 (read only) / Troubleshooting / Arduino Serial Monitor (Ubuntu 10.04 64bit) on: January 22, 2011, 11:15:50 pm
Hello,

I am just getting started with Arduino development and am having a difficult time getting it  to interface with Java. I am using Eclipse and trying to read serial data. I just noticed that I am getting the same error in Eclipse that I am getting in arduino IDE

I had been using the serial monitor in the IDE without a problem, that is up until I executed this command:
Code:
stty -F /dev/ttyUSB0 cs8 9600 ignbrk -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts

as directed at:  arduino.cc/playground/Interfacing/LinuxTTY

and was then able to read the serial output of the arduino via the terminal with: tail -f /dev/ttyUSB0
but at this point I noticed that I was no longer able to use the serial monitor in the IDE. This whole time I had been using arduino-0018 installed via the ppa. I tried downloading arduino-0021 and am getting the same errors, I tried the 64 bit and the 32 bit and also tried copying RXTXcomm.jar and librxtxSerial.so from rxtx2.2pre2 release into arduino-00xx/lib/

Here is what I'm stuck on:
Code:
corbin@skillTop:/usr/local/share/arduino-0021$ ./arduino
Experimental:  JNI_OnLoad called.
WARNING:  RXTX Version mismatch
      Jar version = RXTX-2.2pre1
      native lib Version = RXTX-2.1-7
RXTX Warning:  Removing stale lock file. /var/lock/LCK..ttyUSB0
Binary sketch size: 2476 bytes (of a 30720 byte maximum)
#
# A fatal error has been detected by the Java Runtime Environment:
#
#  SIGSEGV (0xb) at pc=0x00007f77df047462, pid=2020, tid=140152811636496
#
# JRE version: 6.0_20-b20
# Java VM: OpenJDK 64-Bit Server VM (19.0-b09 mixed mode linux-amd64 )
# Derivative: IcedTea6 1.9.2
# Distribution: Ubuntu 10.04.1 LTS, package 6b20-1.9.2-0ubuntu1~10.04.1
# Problematic frame:
# C  [librxtxSerial.so+0x6462]  read_byte_array+0x52
#
# An error report file with more information is saved as:
# /usr/local/share/arduino-0021/hs_err_pid2020.log
#
The IDE crashes at this point right as I press the serial monitor button.

anyone have any ideas?
Pages: [1]