Skip to content

Instantly share code, notes, and snippets.

@tkojitu
Created February 27, 2012 14:43
Show Gist options
  • Save tkojitu/1924274 to your computer and use it in GitHub Desktop.
Save tkojitu/1924274 to your computer and use it in GitHub Desktop.
send command to arduino via serial (usb) port.
import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Enumeration;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class SerialSwitch implements ActionListener, Runnable {
private static final String PORT_NAMES[] = {
"/dev/tty.usbserial-A9007UX1", // Mac OS X
"/dev/ttyUSB0", // Linux
"COM3", // Windows
};
private static final int TIME_OUT = 2000;
private static final int DATA_RATE = 9600;
private SerialPort serialPort;
private OutputStream output;
private ByteArrayOutputStream bout;
private OutputStreamWriter writer;
private boolean on;
public SerialSwitch() {
bout = new ByteArrayOutputStream();
writer = new OutputStreamWriter(bout);
}
@SuppressWarnings("CallToThreadDumpStack")
public void initialize() {
CommPortIdentifier portId = findPortId();
if (portId == null) {
System.out.println("Could not find COM port.");
return;
}
try {
serialPort = (SerialPort)portId.open(this.getClass().getName(), TIME_OUT);
serialPort.setSerialPortParams(DATA_RATE,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
output = serialPort.getOutputStream();
serialPort.notifyOnDataAvailable(true);
} catch (PortInUseException
| UnsupportedCommOperationException
| IOException e) {
e.printStackTrace();
}
}
private CommPortIdentifier findPortId() {
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier)portEnum.nextElement();
for (String portName : PORT_NAMES) {
if (currPortId.getName().equals(portName)) {
portId = currPortId;
break;
}
}
}
return portId;
}
public synchronized void close() {
if (serialPort == null) {
return;
}
serialPort.close();
}
private void createAndShowGui() {
JFrame frame = createFrame();
frame.setVisible(true);
}
private JFrame createFrame() {
JFrame frame = new JFrame("SerialSwitch");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(createPane());
frame.pack();
return frame;
}
private JPanel createPane() {
JPanel pane = new JPanel();
pane.add(createButton());
return pane;
}
private JButton createButton() {
JButton button = new JButton("ON");
button.addActionListener(this);
return button;
}
@Override
public void actionPerformed(ActionEvent event) {
JButton button = (JButton)event.getSource();
onButton(button);
}
@SuppressWarnings("CallToThreadDumpStack")
private void onButton(JButton button) {
try {
String command = getCommand();
writer.write(command, 0, command.length());
writer.flush();
bout.writeTo(output);
button.setText(getButtonText());
on = !on;
bout.reset();
} catch (IOException e) {
e.printStackTrace();
}
}
private String getCommand() {
return on ? "OFF\n" : "ON\n";
}
private String getButtonText() {
return on ? "ON" : "OFF";
}
@Override
public void run() {
createAndShowGui();
}
public static void main(String[] args) throws Exception {
SerialSwitch main = new SerialSwitch();
main.initialize();
SwingUtilities.invokeLater(main);
System.out.println("Started");
}
}
// arduino sketch (need Arduino IDE 1.0)
class Control {
public:
int pin;
public:
Control(int pin) : pin(pin) {}
~Control() {}
void pinMode(int mode) {
::pinMode(pin, mode);
}
void pinModeIn() {
pinMode(INPUT);
}
void pinModeOut() {
pinMode(OUTPUT);
}
void digitalWrite(int value) {
::digitalWrite(pin, value);
}
void digitalWriteHigh() {
digitalWrite(HIGH);
}
void digitalWriteLow() {
digitalWrite(LOW);
}
};
class App {
public:
Control* led;
bool status;
char buffer[128];
String line;
public:
App() : led(NULL), status(false) {
led = new Control(13);
clearBuffer();
}
~App() {
delete led;
}
void clearBuffer() {
for (size_t i = 0; i < sizeof(buffer); ++i) {
buffer[i] = 0;
}
}
void setup() {
led->pinModeOut();
Serial.begin(9600);
Serial.setTimeout(1000);
}
void loop() {
int n = readLine(buffer, sizeof(buffer), line);
if (n <= 0) {
return;
}
if (line == "ON") {
led->digitalWriteHigh();
} else if (line == "OFF") {
led->digitalWriteLow();
}
}
int readLine(char* buf, int bufsiz, String& ret) {
if (Serial.available() <= 0) {
return -1;
}
int n = Serial.readBytesUntil('\n', buf, bufsiz - 1);
if (n >= 0) {
buf[n] = '\0';
ret = buf;
}
return n;
}
};
void* gApp;
void setup() {
App* app = new App();
app->setup();
gApp = app;
}
void loop() {
((App*)gApp)->loop();
}
@arfahussain
Copy link

Please can u help me to code in java like if I give the input 'A' it will send the result to arduino UNO and on the LED of 'A'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment