I am reading serial data from an arduino sketch that I uploaded to a teensy 2.0 / this also occurs when running a regular arduino. I am then splitting the strings and converting into an integer array with Processing’s int() function, in order to be able to trigger sounds. The arduino sketch is reading in capacitive sensor data. It runs well for about 10-15s and then starts throwing up the following error.
Exception in thread "Animation Thread" java.lang.NullPointerException
at processing.core.PApplet.parseInt(PApplet.java:9127)
at processing.core.PApplet.parseInt(PApplet.java:9113)
at NightGames_Tree.draw(NightGames_Tree.java:59)
at processing.core.PApplet.handleDraw(PApplet.java:2266)
at processing.core.PGraphicsJava2D.requestDraw(PGraphicsJava2D.java:243)
at processing.core.PApplet.run(PApplet.java:2140)
at java.lang.Thread.run(Thread.java:695)
My code is as follows:
In Arduino:
#include <CapacitiveSensor.h>
CapacitiveSensor cs_4_2 = CapacitiveSensor(4,2);
void setup()
{
cs_4_2.set_CS_AutocaL_Millis(0xFFFFFFFF); // turn off autocalibrate on channel 1 - just as an example
Serial.begin(9600);
}
void loop()
{
long start = millis();
long total1 = cs_4_2.capacitiveSensor(30);
Serial.print(millis() - start); // check on performance in milliseconds
Serial.print("\t");
Serial.print(total1); // print sensor output 1
Serial.println("\t");
delay(100);
}
In Processing:
import ddf.minim.spi.*;
import ddf.minim.signals.*;
import ddf.minim.*;
import ddf.minim.analysis.*;
import ddf.minim.ugens.*;
import ddf.minim.effects.*;
import processing.serial.*;
Minim minim;
AudioPlayer tree1;
AudioPlayer tree2;
Serial myPort;
String val;
void setup(){
String portName = Serial.list()[12]; // calls on the port which teensy is on
myPort = new Serial(this, portName, 9600);
println(Serial.list()); // prints list of ports that processing can access
//setup sound
minim = new Minim(this);
tree1 = minim.loadFile("tree1.aif");
}
void draw()
{
if (myPort.available() > 0) {
val = myPort.readStringUntil('\n');
int[] list = int(split(val, '\t')); // splits string into list based on tab after
int sum = 0;
int sum1 = 0;
// print(list.length);
sum = sum + list[0];
sum1 = sum1 + list[1];
print(sum);
print('\t');
print(sum1);
print('\t');
print('\n');
//print(val);
if (sum1 > 500) {
tree1.play(0);
} else if (sum1 <500){
}
}
}
When the error shows up after running for a while, Processing highlights this line of code
int[] list = int(split(val, '\t'));
Thanks in advance for any help. I am running this on a Mac.
I ran this on a Windows box, using Processing 3.0a4 and Arduino 1.6.3
On Arduino, I commented out everything having to do with the capacitive sensor library because I didn't have it. `
//#include <CapacitiveSensor.h>
//CapacitiveSensor cs_4_2 = CapacitiveSensor(4,2);
void setup()
{
// cs_4_2.set_CS_AutocaL_Millis(0xFFFFFFFF);
// turn off autocalibrate on channel 1 - just as an example
Serial.begin(9600);
}
void loop()
{
long start = millis();
// long total1 = cs_4_2.capacitiveSensor(30);
Serial.print(millis() - start);
// check on performance in milliseconds
Serial.print("\t");
//Serial.print(total1); // print sensor output 1
Serial.println("\t");
delay(100);
}
In Processing I commented out the line with the sound file.
The error I got pointed to this line:
int[] list = int(split(val, '\t'));
It seems possible that there is a type mismatch that allows the list to stream for a short bit but them jams up the processor.
Turns out processing was detecting a null object so adding a check for null objects solved the problem. The condensed code is:
import processing.serial.*;
Serial myPort;
String val;
void setup(){
String portName = Serial.list()[12]; // calls on the port which teensy is on
myPort = new Serial(this, portName, 9600);
}
void draw()
{
if (myPort.available() > 0) {
val = myPort.readStringUntil('\n');
if (val!=null){
int[] list = int(split(val, '\t')); // splits string into list based on tab
int sum = 0;
int sum1 = 0;
int sum2 = 0;
sum = sum + list[0];
sum1 = sum1 + list[1];
sum2 = sum2 + list[2];
print(sum);
print('\t');
print(sum1);
print('\t');
print(sum2);
print('\t');
print('\n');
}
}
}
Related
implement the SJF algorithm in both "Non-preemptive" and "Preemptive" mode
I need to print out the correct execution order of the sequence of process, you need to print them out in the console, e.g. 5, 3, 1, 2, 4, ... (each number is the process ID), computing and printing out the average waiting time, computing and printing out average response time.
This is the code that I have tried so far i need help with the /*CPU scheduling algorithm 2: shortest job first (SJF), non-preemptive or preemptive mode, section ....
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Process {
int id; //The unique ID for each process
Instant ready_time; //store the time that the process arrives at the ready queue
int burst_time; //the time requires CPU to execute the process
Instant finish_time; //The time that the current process is finished by CPU
Instant start_time; //The time that the CPU picks the process for execution
String status;
Process(int id)
{
this.id = id;
status = "new";
}
/*
* Display the process info: [id]: ready_time, burst_time
* */
void disp()
{
System.out.println("["+id+"]: ready: " + ready_time.atZone(ZoneOffset.UTC).getSecond() + "." + ready_time.atZone(ZoneOffset.UTC).getNano() + ", CPU: " + burst_time);
System.out.println(" start: " + start_time.atZone(ZoneOffset.UTC).getSecond() + "." + start_time.atZone(ZoneOffset.UTC).getNano() + ", finish: " + finish_time.atZone(ZoneOffset.UTC).getSecond() + "." + finish_time.atZone(ZoneOffset.UTC).getNano());
}
void run() {
status = "running";
System.out.println("Process " + id + " is running...");
terminate();
}
void terminate() {
status = "terminated";
System.out.println("Process " + id + " is terminated");
}
/*CPU scheduling algorithm 1: first come first serve*/
public static void fcfs(List<Process> list)
{
//Hold all the processes that have been executed
List<Process> finished_list = new ArrayList<Process>();
//As long as there is one or more processes in the ready queue, CPU should execute them
while(list.size() > 0)
{
//Initially assume the first item has the smallest arrive_time
Instant min_arrive = list.get(0).ready_time;
int min_idx = 0;
//Use a loop to compare the "min_arrive" with each process in the list
for(int i = 1; i < list.size(); i++)
{
//Compare each process with the current recorded "min_arrive"
if(min_arrive.compareTo(list.get(i).ready_time) > 0)
{
min_arrive = list.get(i).ready_time;
min_idx = i;
}
}
//After the loop you should find the smallest arrive_time
if(list.size() == 10)
{
//The current process is the first of all
list.get(min_idx).start_time = list.get(min_idx).ready_time;
}
else
{
//If the current process ready_time is after last process's finish time
if(list.get(min_idx).ready_time.compareTo(finished_list.get(finished_list.size() - 1).finish_time) > 0)
{
list.get(min_idx).start_time = list.get(min_idx).ready_time;
}
else {
list.get(min_idx).start_time = finished_list.get(finished_list.size() - 1).finish_time;
}
}
list.get(min_idx).finish_time
= list.get(min_idx).start_time.plus(Duration.ofMillis(list.get(min_idx).burst_time));
//Add the current process to the finish list
finished_list.add(list.get(min_idx));
//Remove the current process from list
list.remove(min_idx);
}
//Print out the finish list order
System.out.println("Finish list: ");
double waiting_time = 0.0;
for(int i = 0; i < finished_list.size(); i++)
{
finished_list.get(i).disp();
waiting_time += (double)Duration.between(finished_list.get(i).ready_time, finished_list.get(i).start_time).toMillis();
}
//Print out the average waiting time
System.out.println("Average Waiting Time: " + waiting_time/10.0);
}
/*CPU scheduling algorithm 2: shortest job first (SJF), non-preemptive or preemptive mode, indicated by the 3rd parameter "mode" (0: non-preemptive 1: preemptive*/
public static void sjf(List<Process> list, Instant cpu_time, int mode)
{
//Instead of using the earliest process as the CPU available time, you use random()
//to generate a random CPU start time
}
public static void main(String args[])
{
List<Process> list = new ArrayList<Process>();
Instant cur_time = Instant.now();
Random rand_cpu = new Random();
Instant cpu_time = cur_time.plus(Duration.ofMillis(rand_cpu.nextInt(1000)));
for(int i = 0; i < 10; i++)
{
//Create a process by using "i" as the process ID
Process p = new Process(i);
//Generate random number between 0 and 2000 by using Random() class
Random rand = new Random();
int value = rand.nextInt(2000);
//Use the "millisecond" component of the local time to plus the random number
// as the ready_time value for the current process
Duration duration = Duration.ofMillis(value);
p.ready_time = cur_time.plus(duration);
//Generate another random number (between 0 and 2000) to assign the burst_time
p.burst_time = rand.nextInt(2000);
p.start_time = p.ready_time;
p.finish_time = p.ready_time;
//Add this process into the list
list.add(p);
}
//Display all the process
for(int i = 0; i < list.size(); i++)
{
list.get(i).disp();
}
//Perform "First come first serve" CPU scheduling
//fcfs(list);
//Perform "Shortest Job First" CPU scheduling
sjf(list, cpu_time);
}
}
This question already has answers here:
How do I write a correct micro-benchmark in Java?
(11 answers)
Closed 4 years ago.
please i need help i am writing this code to be able to display my execution time anytime i run a program but i usually get different time even when its the same input
after importing all this
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/** Class KnuthMorrisPratt **/
public class Knuth1
{
/** Failure array **/
private int[] failure;
/** Constructor **/
public Knuth1(String text, String pat)
{
/** pre construct failure array for a pattern **/
failure = new int[pat.length()];
fail(pat);
/** find match **/
int pos = posMatch(text, pat);
if (pos == -1)
System.out.println("\nNo match found");
else
System.out.println("\nMatch found at index "+ pos);
}
/** Failure function for a pattern **/
private void fail(String pat)
{
int n = pat.length();
failure[0] = -1;
for (int j = 1; j < n; j++)
{
int i = failure[j - 1];
while ((pat.charAt(j) != pat.charAt(i + 1)) && i >= 0)
i = failure[i];
if (pat.charAt(j) == pat.charAt(i + 1))
failure[j] = i + 1;
else
failure[j] = -1;
}
}
/** Function to find match for a pattern **/
private int posMatch(String text, String pat)
{
int i = 0, j = 0;
int lens = text.length();
int lenp = pat.length();
while (i < lens && j < lenp)
{
if (text.charAt(i) == pat.charAt(j))
{
i++;
j++;
}
else if (j == 0)
i++;
else
j = failure[j - 1] + 1;
}
return ((j == lenp) ? (i - lenp) : -1);
}
/** Main Function **/
public static void main(String[] args) throws IOException
{
//i think its here were i get the input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in) ));
System.out.println("Knuth Morris Pratt Test\n");
System.out.println("\nEnter Text: ");
String text = br.readLine();
System.out.print("\nEnter Pattern");
String pattern = br.readLine();
double starttime = System.nanoTime();
Knuth1 kmp = new Knuth1(text, pattern);
double endtime = System.nanoTime();
double executiontime = (endtime - starttime )/1000000000;
// System.out.printf("%.4f","Execution Time = "+ executiontime + " Seconds");
System.out.print("Execution Time = ");
System.out.format("%.4f", executiontime);
System.out.print(" Seconds");
// System.out.println(starttime);
// System.out.println(endtime);
//I love programming with JAVA and Php. It’s fun and interesting.
}
}
this code will check an input strings and pick out the unique word and the try to also display the execution time for the program... what i really want now is to make sure the execution time remain the same when i input the same input.
If you don't care about reusing the timed functionality, use System.nanoTime()
long before;
long after;
// Get time before
before = System.nanoTime();
// Code you want to execute here
// Get time after
after = System.nanoTime();
// Calculate duration
long diff = after - before;
You can encapsulate any code you want into a Runnable or using any of Java 8's new Predicate or Function interfaces which are very similar. You can put the code that you want to run in a lambda expression (like an anonymous function) and pass it to a static method that calculates in nanoseconds the amount of time it takes the runnable object to execute.
This is more code than what is necessary, but it reusable in that you don't have to keep writing start = System.currentTimeMillis() or System.nanoTime()and doing arithmetic every time you want to time something. You can put this function in your static library and use it whenever you want.
/**
* Times a runnable. Note, there
* is probably overhead associated with
* creating a Runnable object, but if
* assume that's constant for all Runnable
* objects, then we can simply ignore it
*
* #param runnable Runnable to run
* #return Number of nanoseconds it took to run the Runnable
*/
public static long timedAction(Runnable runnable) {
long before;
long after;
before = System.nanoTime();
runnable.run();
after = System.nanoTime();
return after - before;
}
This is how I use this code block:
public static void main(String[] args) throws Exception {
final int numKeys = 1000000;
// Builds an AVL tree
Runnable snippet = () -> {
Tree<Integer, Object> avl = new AVLTree<>();
for (int i = 0; i < numKeys; i++) {
avl.insert(i, i);
}
};
long nanoSecond = Util.timedAction(snippet);
double seconds = Mathematics.nanosecondsToSeconds(nanoSecond);
System.out.println(seconds);
}
Output:
0.493316448
I am trying to get Accelerometer data into my Java application from Arduino at its IMU. When I run my Arduino program on Arduino IDE and bring up Serial Monitor data flow is really good. Unfortunatelly when I try to run my Java code something strange happens. I have to wait for 10 seconds and then about 1000 lines appear immediately. Then i have to wait for another 10-20 seconds and another 1000 lines of data appears.. Is Arduino sending data in packages ? Can't I get a single value right after its given to me from IMU ?
Arduino code :
#include <MPU9250.h>
#include <quaternionFilters.h>
#define AHRS true // Set to false for basic data read
#define SerialDebug true // Set to true to get Serial output for debugging
// Pin definitions
int intPin = 12; // These can be changed, 2 and 3 are the Arduinos ext int pins
int myLed = 13; // Set up pin 13 led for toggling
MPU9250 myIMU;
void setup()
{
Wire.begin();
Serial.begin(38400);
pinMode(intPin, INPUT);
digitalWrite(intPin, LOW);
pinMode(myLed, OUTPUT);
digitalWrite(myLed, HIGH);
byte c = myIMU.readByte(MPU9250_ADDRESS, WHO_AM_I_MPU9250);
if (c == 0x71) // WHO_AM_I should always be 0x68
{
myIMU.MPU9250SelfTest(myIMU.SelfTest);
myIMU.calibrateMPU9250(myIMU.gyroBias, myIMU.accelBias);
myIMU.initMPU9250();
} // if (c == 0x71)
else
{
while(1) ;
}
}
void loop()
{
if (myIMU.readByte(MPU9250_ADDRESS, INT_STATUS) & 0x01)
{
myIMU.readAccelData(myIMU.accelCount); // Read the x/y/z adc values
myIMU.getAres();
myIMU.ax = (float)myIMU.accelCount[0]*myIMU.aRes; // - accelBias[0];
myIMU.ay = (float)myIMU.accelCount[1]*myIMU.aRes; // - accelBias[1];
myIMU.az = (float)myIMU.accelCount[2]*myIMU.aRes; // - accelBias[2];
}
myIMU.delt_t = millis() - myIMU.count;
if (myIMU.delt_t>20) // waiting some time to get less data
{
if(SerialDebug)
{
Serial.println(myIMU.ay*1000);
}
myIMU.count = millis();
myIMU.sumCount = 0;
myIMU.sum = 0;
}
}
Java code :
package perkusja;
import com.fazecast.jSerialComm.*;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JSlider;
public class Perkusja {
public static void main(String[] args) {
SerialPort[] ports = SerialPort.getCommPorts();
System.out.println("Select a port:");
int i = 1;
for(SerialPort port : ports)
System.out.println(i++ + ": " + port.getSystemPortName());
Scanner s = new Scanner(System.in);
int chosenPort = s.nextInt();
SerialPort serialPort = ports[chosenPort - 1];
if(serialPort.openPort())
System.out.println("Port opened successfully.");
else {
System.out.println("Unable to open the port.");
return;
}
serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING, 0, 0);
Scanner data = new Scanner(serialPort.getInputStream());
int counter =0;
while(data.hasNextLine()){
try{
// float kupa = data.nextFloat();
System.out.println(data.nextLine());
System.out.println("Line number : " + counter++);
}catch(Exception e){
System.out.println("ERROR");}
}
}
}
I've been following this tutorial : https://www.youtube.com/watch?v=8B6j_yr9H8g&t=392s
Im using Arduino ProMicro from sparkfun and IMU - MPU9250 also from sparkfun
I will run the program over very slow ssh connection. Will it slow down or block the
System.out.println();
on big loads of printing. So if it prints few gigabytes right into console, but my connection is slow - where undiplayed data will appear? what is the size of tty memory? If I will lose connection for a while - will it run still?
No. PrintWriter does not wait for confirmation of completion.
Will it block the program it tty will have latency
Java's console output is blocking, so potentially your code may block, especially when you writing a lot of data.
what is the size of tty memory?
I am pretty sure that it depends on your kernel, this old thread suggests that it was 4096 bytes at some moment:
I've looked in the kernel code (linux\drivers\char\serial.c) and there is a #define called SERIAL_XMIT_SIZE. At first I thought maybe I could change that but it seems that the transmit buffer is actually fixed to be a memory page (4k).
If I will lose connection for a while - will it run still?
Yes, and if there is no one connected to the tty, then it will run much faster, as it will be able to discard the data.
Also small test application that simulates your use-case.
Echo.java
import java.io.IOException;
public class Echo {
public static void main(String[] args) throws InterruptedException, IOException {
final byte[] data = new byte[Test.BODY_LENGTH + Test.END_MARKER.length];
int index = 0;
outer: while (true) {
data[index++] = (byte) System.in.read();
final int dataOffset = index - Test.END_MARKER.length;
if (dataOffset < 0) {
continue;
}
for (int i = 0; i < Test.END_MARKER.length; i++) {
if (data[dataOffset + i] != Test.END_MARKER[i]) {
continue outer;
}
}
System.out.print(new String(data, 0, index));
return;
}
}
}
Test.java
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
public class Test {
public static final byte[] END_MARKER = "$TERMINATE$".getBytes();
public static final int BODY_LENGTH = 1024768;
public static void main(String[] args) throws IOException, InterruptedException {
StringBuilder data = new StringBuilder();
for (int i = 0; i < BODY_LENGTH; i++) {
data.append((char) ('a' + ThreadLocalRandom.current().nextInt(('z' - 'a' + 1))));
}
final Process process = new ProcessBuilder("java", Test.class.getPackage().getName() + ".Echo")
.directory(new File("out/production/week 3")) // Change to your output directory
.start();
process.getOutputStream().write(data.toString().getBytes());
process.getOutputStream().write(END_MARKER);
process.getOutputStream().flush();
System.out.println("Written!");
final boolean exitedAfterWroteData = process.waitFor(5, TimeUnit.SECONDS);
System.out.println(exitedAfterWroteData ? "Complete" : "Running"); // Will print running after 5 seconds
int read = 0;
while (process.getInputStream().read() > -1) {
read++;
}
if (read != data.toString().getBytes().length + END_MARKER.length) {
throw new IllegalStateException("Expected echo to print exactly " + BODY_LENGTH + END_MARKER.length + " symbols!");
}
final boolean exitedAfterWeReadData = process.waitFor(50, TimeUnit.MILLISECONDS);
System.out.println(exitedAfterWeReadData ? "Complete" : "Running"); // Will print complete after a few milliseconds
}
}
I have been trying to get audio signal from an arduino microphone. First I setup my arduino in Free Running Mode, and then I wait for a message from Processing that is a capital A. When Processing sends the serial signal, my arduino should send back 16 audio amplitude samples. Then, processing should take those 16 audio samples and pass them by the Fast Fourier Transform in orden to get a real time frequency spectrum. However, it seems that my Arduino never detects the capital A, and also, if I try to send the samples from my Arduino without waiting for the capital A, when Processing gets the samples it seems something went wrong with the serial communication. I tried with many arduinos and different serial cables to be sure it was no the problem. Here you are the arduino code:
// Arrays to save our results in
int values[16];
// Define various ADC prescaler
const unsigned char PS_16 = (1 << ADPS2);
const unsigned char PS_32 = (1 << ADPS2) | (1 << ADPS0);
const unsigned char PS_64 = (1 << ADPS2) | (1 << ADPS1);
const unsigned char PS_128 = (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);
// Setup the serial port and pin 2
void setup() {
Serial.begin(115200);
pinMode(2, INPUT);
// set up the ADC
ADCSRA &= ~PS_128; // remove bits set by Arduino library
// you can choose a prescaler from above.
// PS_16, PS_32, PS_64 or PS_128
ADCSRA |= PS_64; // set our own prescaler to 64
}
void loop() {
unsigned int i;
for(i=0;i<16;i++) {
values[i] = analogRead(2);
}
if(Serial.available() > 0) {
char c = Serial.read();
if(c == 'A') {
for(i=0;i<16;i++) {
Serial.println(values[i]);
}
}
}
delay(10);
}
Here you are the processing code:
import processing.serial.*;
import ddf.minim.analysis.*;
FFT fft;
Serial myPort; // Create object from Serial class
void setup()
{
String portName = Serial.list()[0];
myPort = new Serial(this, portName, 115200);
size(800, 600);
background(255);
fft = new FFT(16, 16000);
}
String mensaje;
float[] magnitudes = new float[16];
int contador = 0;
byte request = true;
void draw()
{
if(request) {
myPort.write('A');//Solicita nuevos datos.
request = false;
}
while(!request) {
if(myPort.available()>0) {
mensaje = myPort.readStringUntil(13);
print(" mensaje: "+mensaje);
if(mensaje != null){
magnitudes[contador++] = int(mensaje);
}
}
if(contador >= 15) {
contador=0;
fft.forward(magnitudes);
request = true;
fill(100);
rect(0,0,800,800);
for (int i = 0; i < 15; i++) {
fill(200);
rect(i*30+10, 0, 10, fft.getBand(i) * 0.1);
}
}
}
}
Thank you a lot for your attention!