Serial COM Port Selection by DropDownList in processing - drop-down-menu

I wrote a program in Processing 2.1.2 to establish a communication via serial Port between two machines. On my laptop, it was working fine but on my desktop where more than one serial ports are available, it is not detecting my functional serial COM port.
So now I want them to appear on Combo Button and I will able to select one from them.
Can you guide me on how do I resolve this issue?
import processing.serial.*;
String input;
Serial port;
void setup() {
size(448, 299,P3D);
println(Serial.list());
port = new Serial(this,Serial.list()[0], 9600);
port.bufferUntil('\n');
}
void draw() {
background(0);
}
void serialEvent(Serial port)
{
input = port.readString();
if(input != null) {
String[] values = split(input, " ");
println(values[0]);
println(values[1]);
println(values[2]);
}
}

As mentioned in the comment, it is possible to use a UI library to display a dropdown. First you have to choose a library, like for example controlP5 which is very popular with Processing. You may choose to use Swing with a native look & feel or G4P. That's totally up to you.
After that it should be a matter of plugging the serial ports list into the dropdown and opening the serial connection on the dropdown listener/callback.
Bellow is a proof of concept sketch based on the controlP5dropdownlist example that comes with the library:
import processing.serial.*;
import controlP5.*;
ControlP5 cp5;
DropdownList serialPortsList;
Serial serialPort;
final int BAUD_RATE = 9600;
void setup() {
size(700, 400,P3D);
String[] portNames = Serial.list();
cp5 = new ControlP5(this);
// create a DropdownList
serialPortsList = cp5.addDropdownList("serial ports").setPosition(10, 10).setWidth(200);
for(int i = 0 ; i < portNames.length; i++) serialPortsList.addItem(portNames[i], i);
}
void controlEvent(ControlEvent theEvent) {
// DropdownList is of type ControlGroup.
// A controlEvent will be triggered from inside the ControlGroup class.
// therefore you need to check the originator of the Event with
// if (theEvent.isGroup())
// to avoid an error message thrown by controlP5.
if (theEvent.isGroup()) {
// check if the Event was triggered from a ControlGroup
println("event from group : "+theEvent.getGroup().getValue()+" from "+theEvent.getGroup());
//check if there's a serial port open already, if so, close it
if(serialPort != null){
serialPort.stop();
serialPort = null;
}
//open the selected core
String portName = serialPortsList.getItem((int)theEvent.getValue()).getName();
try{
serialPort = new Serial(this,portName,BAUD_RATE);
}catch(Exception e){
System.err.println("Error opening serial port " + portName);
e.printStackTrace();
}
}
else if (theEvent.isController()) {
println("event from controller : "+theEvent.getController().getValue()+" from "+theEvent.getController());
}
}
void draw() {
background(128);
}
Also notice any existing connection will be closed when choosing a new serial port and errors handling opening the serial port are handled so the program doesn't crash in case there are issues.
For example, on OSX you get bluetooth serial ports, which may or may not be available or of use:

for processing 3.3.7 doesn't work at all for one string
String portName = serialPortsList.getItem((int)theEvent.getValue()).getName();
So i spent a lot of my neurons and nervs, but my fix is getName change toString();
and
String portName = serialPortsList.getItem((int)theEvent.getValue()).toString();
I don't understand why getName() gives me "The function doesnt exist" but toString works properly. Anybody can explain?

For variable:
String[] portNames = Serial.list();
change to global variable:
String[] portNames;
In:
void setup()
change:
String[] portNames = Serial.list();
to:
portNames = Serial.list();
In code:
String portName = serialPortsList.getItem((int)theEvent.getValue()).toString();
change to:
String portName =portNames.toString();

Related

How to add a function to dropdown list?

I've added a drop down list in processing using controlp5 library. I want to transmit data serially to Arduino when certain item is selected in the list. How to add the control for this purpose?
Here's my code:
void setup{
d1 = cp5.addDropdownList("color")
.setPosition(((width/4)-50), ((height/2)-40))
.setBackgroundColor(color(37, 126, 214))
.setFont(font1)
.setItemHeight(25)
.setBarHeight(20)
.addItem("red ", d1)
.addItem("blue ", d1)
.addItem("green ", d1)
}
I want to send a character 'r','b','g' to Arduino when each item is selected respectively. Suggest me how to write the code for my purpose.
Dropdown list is deprecated as the author says in the example, I think the simplest way is to implement ScrollableList, which is more flexible, and send the data though Serial Port to Arduino.
// Import java utils, for the list to add to the scrollable list
import java.util.*;
// Import ControlP5 library and declare it
import controlP5.*;
ControlP5 cp5;
// Import the Serial port and declare it
import processing.serial.*;
Serial myPort; // Create object from Serial class
void setup() {
size(400, 400);
// Initialize the Serial port
String portName = Serial.list()[0];
myPort = new Serial(this, portName, 9600);-
// Initialize the dropdown list
cp5 = new ControlP5(this);
List l = Arrays.asList("red", "green", "blue");
/* add a ScrollableList, by default it behaves like a DropdownList */
cp5.addScrollableList("dropdown")
.setPosition(100, 100)
.setSize(200, 100)
.setBarHeight(20)
.setItemHeight(20)
.addItems(l)
;
}
void draw() {
background(255);
}
// Dropdown callback function fromthe ScrollableList, triggered when you select an item
void dropdown(int n) {
/* request the selected item based on index n and store in a char */
String string = cp5.get(ScrollableList.class, "dropdown").getItem(n).get("name").toString();
char c = string.charAt(0);
// Write the char to the serial port
myPort.write(c);
}
On the Arduino side
char val; // Data received from the serial port
void setup() {
Serial.begin(9600); // Start serial communication at 9600 bps
}
void loop() {
while (Serial.available()) { // If data is available to read,
val = Serial.read(); // read it and store it in val
}
}

Pulse sensor coding for Netduino Plus 2 gone wrong

I'm currently doing a project on Netduino Plus 2 using .net micro framework which requires me to code for a pulse sensor. I have tried finding codes for pulse sensor but to no avail. I tried using AnalogInput codes for pulse sensor but the output values seemed wrong (there was a constant high value despite no heartbeat placed near the sensor). Please advise!
Here are my current codes for the heartbeat sensor:
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.Netduino;
namespace heartrate
{
public class Program
{
public static void Main()
{
SecretLabs.NETMF.Hardware.AnalogInput rate =
new SecretLabs.NETMF.Hardware.AnalogInput(Pins.GPIO_PIN_A0);
int sensorvalue = 0;
while (true)
{
sensorvalue = rate.Read();
Debug.Print("" + sensorvalue);
Thread.Sleep(1000);
}
}
}
}
Here are the specs of the sensor, how it looks like and how it is connected.
http://www.elecrow.com/wiki/index.php?title=Pulse_Sensor
(This tutorial is for arduino, but I think the wiring is similar to that of Netduino)
Hard to tell without specs on your pulse device and how it is attached. For Analog input & output in my latest project (https://github.com/osstekz/cncBuddy) I use classes InputPort & OutputPort (Microsoft.SPOT.Hardware)
ex:
public NESControllerAdapter(Cpu.Pin pinClk, Cpu.Pin pinLatch, Cpu.Pin pinData1/*, Cpu.Pin pinData2 = Cpu.Pin.GPIO_NONE*/) {
// Binds to all pins
this._outpClk = new OutputPort(pinClk, false);
this._outpLatch = new OutputPort(pinLatch, false);
this._inpData1 = new InputPort(pinData1, false, Port.ResistorMode.Disabled);
//if (pinData2 != Cpu.Pin.GPIO_NONE) this._inpData2 = new InputPort(pinData2, false, Port.ResistorMode.Disabled);
}
...then like your rate.Read(); loop
public int ButtonPressed() {
// Locks all parms
this._PinTick(this._outpLatch);
// Reads plug state value
for (int i = 0; i < CncBuddyShared.iTOTALNESCONTROLLERBUTTONS; ++i) {
// Read the value, if true return this index as the first pressed button
if (this._inpData1.Read() == false) return i;
// Selects the next value
this._PinTick(this._outpClk);
}
return NESCONTROLLER_PRESSEDBUTTOM_NONE;
}

In Processing, using serial port, why is .equals not returning true?

I am using Processing to display data coming into the serial port.
I have simple string values coming into the serial port.
I have cut down all my code to this basic point of failure and I cannot understand why it fails. The if statement never evaluates to true. (I'm not trying to compare strings with = or == )
Please help if you know why this is happening :) I'd really appreciate an answer.
Ugh Alright then, since I don't have a reputation of 10, I won't post the helpful screenshot.
Here is the code that fails:
enter code here
import processing.serial.*;
Serial myPort;
String val; //Data recieved from the serial port
void setup() {
size(400,300);
String portName = Serial.list()[2]; //change the 0 to a 1 or 2 etc. to match your port //1 or 2 for USB on the Mac
myPort = new Serial(this, portName, 9600);
myPort.bufferUntil('\n');
}
void serialEvent (Serial myPort){
val = myPort.readStringUntil('\n');
print(val);
if(val != null){
if(val.equals("New sample set")){
print("yes\n");
} else {
print("not equal\n");
}
}
}
void draw() {
//The serialEvent controls the display
}
I have tried taking out the spaces and making it only one letter, but this did not help. I have tried using if(val.equals("New sample set")==true) but that didn't help either.
Alrighty, it only took a few hours but I have answered my own question :)
Yes, comparing strings must be done with .equals()
and
Yes, they must be trimmed so that all line feed characters are eliminated.
I was using trim incorrectly.
Simply saying myString.trim(); will not do.
this returns a string, so it needs to be placed somewhere; here's how:
myString=myString.trim();
I know, kind of obvious to the experienced coder, but I just couldn't see it. And I thought bufferUntil('\n') would only buffer the stuff before the \n... I guess not.
Hope the hours I spent in this silly little "boggle" can help someone else!
:)
Happy coding!!!
Successful processing code below:
import processing.serial.*;
Serial myPort;
String val; //Data recieved from the serial port
void setup() {
size(400,300);
String portName = Serial.list()[2]; //change the 0 to a 1 or 2 etc. to match your port //1 or 2 for USB on the Mac
myPort = new Serial(this, portName, 9600);
myPort.bufferUntil('\n');
}
void serialEvent (Serial myPort){
val = myPort.readStringUntil('\n');
print("After reading serial, val is "+val+".\n");
val=val.trim();
print("After trimming, val is "+val+".\n");
if(val != null){
print("After comparing to null, val is "+val+".\n");
if("N".equals(val)){
print("yes\n");
} else {
print(val+" is not equal to \"N\".\n");
}
}
}
void draw() {
//The serialEvent controls the display
}

Developing iTunes like application in c#

I need to develop an application in c# that could automatically detect an iPhone when it is connected to the system and read a particular file for the iPhone file system. I basically want this file to be downloaded automatically from device to the PC. I used USBpcap tool that suggests that iTunes connects to phone using some XML format. Any help or insight greatly appreciated. Is there any documentation of Third party APIs that can get me started? There are some applications that can replicate iTunes functionality e.g Copytrans
Is there any protocol or APIs provided by Apple?
I have been digging the internet and found this link Layered communication for iPhone.
Also I am using the LibUsbDotNet libraries for communicating to the usb device(Example). Can any one suggest which EndPoints should be used.
It seems to me that I have to implement usbmuxd in windows application. It is a multilayer protocol. There must be some libraries that implement usbmuxd(I dont think I have to implement the protocol all by my self)
I dont have much idea about iTunes communication as well as USB communication. I am adding as much information as I can(of course with the things I come up with in my R&D). Any help is highly appreciated.
public static DateTime LastDataEventDate = DateTime.Now;
public static UsbDevice MyUsbDevice;
#region SET YOUR USB Vendor and Product ID!
public static UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(1452, 4768);
#endregion
private void LibUSB()
{
ErrorCode ec = ErrorCode.None;
try
{
// Find and open the usb device.
MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
// If the device is open and ready
if (MyUsbDevice == null)
throw new Exception("Device Not Found.");
// If this is a "whole" usb device (libusb-win32, linux libusb)
// it will have an IUsbDevice interface. If not (WinUSB) the
// variable will be null indicating this is an interface of a
// device.
IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
if (!ReferenceEquals(wholeUsbDevice, null))
{
// This is a "whole" USB device. Before it can be used,
// the desired configuration and interface must be selected.
// Select config #1
wholeUsbDevice.SetConfiguration(1);
// Claim interface #0.
wholeUsbDevice.ClaimInterface(0);
}
// open read endpoint 1.
UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep03);
// open write endpoint 1.
UsbEndpointWriter writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep02);
int bytesWritten;
ec = writer.Write(usbmux_header.GetBytes(), 2000, out bytesWritten);
if (ec != ErrorCode.None)
throw new Exception(UsbDevice.LastErrorString);
byte[] readBuffer = new byte[1024];
while (ec == ErrorCode.None)
{
int bytesRead;
// If the device hasn't sent data in the last 100 milliseconds,
// a timeout error (ec = IoTimedOut) will occur.
ec = reader.Read(readBuffer, 10000, out bytesRead);
if (ec == ErrorCode.Win32Error)
throw new Exception("port not open");
if (bytesRead == 0)
throw new Exception("No more bytes!");
// Write that output to the console.
Console.Write(Encoding.Default.GetString(readBuffer, 0, bytesRead));
}
}
catch (Exception ex)
{
Console.WriteLine();
Console.WriteLine((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
}
finally
{
if (MyUsbDevice != null)
{
if (MyUsbDevice.IsOpen)
{
// If this is a "whole" usb device (libusb-win32, linux libusb-1.0)
// it exposes an IUsbDevice interface. If not (WinUSB) the
// 'wholeUsbDevice' variable will be null indicating this is
// an interface of a device; it does not require or support
// configuration and interface selection.
IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
if (!ReferenceEquals(wholeUsbDevice, null))
{
// Release interface #0.
wholeUsbDevice.ReleaseInterface(0);
}
MyUsbDevice.Close();
}
MyUsbDevice = null;
// Free usb resources
UsbDevice.Exit();
}
}
}
class usbmux_header
{
public static UInt32 length = 10; // length of message, including header
public static UInt32 reserved = 0; // always zero
public static UInt32 type = 3; // message type
public static UInt32 tag = 2; // responses to this query will echo back this tag
public static byte[] GetBytes()
{
byte[] lgth = BitConverter.GetBytes(length);
byte[] res = BitConverter.GetBytes(reserved);
byte[] tpe = BitConverter.GetBytes(type);
byte[] tg = BitConverter.GetBytes(tag);
byte[] retArray = new byte[16];
lgth.CopyTo(retArray, 0);
res.CopyTo(retArray, 4);
tpe.CopyTo(retArray, 8);
tg.CopyTo(retArray, 12);
return retArray;
}
};
I have been trying to send hello packet bytes to iPhone but I am not able to read any response from phone.
To play with ipod you can use SharePodLib
As I understand it, only one client can use the USB connection to iOS at one time. On both macOS and Windows, that one client is usbmux. That library multiplexes TCP connections with higher-level clients, including iTunes, Photos, and (on macOS) the open-source peertalk library.
So on Windows, you wouldn't want to implement your own usbmux, but rather a client that sits on top of that, analogous to peertalk. I haven't seen anything open-source that does this, but a number of developers have accomplished it with their own proprietary software.
If anybody else has pointers about using usbmux on Windows, I'd love to hear about it.
—Dave
You can use imobiledevice-net. It provides a C# API to connect to iOS devices using your PC.
For example, to list all iOS devices connected to your PC, you would run something like this:
ReadOnlyCollection<string> udids;
int count = 0;
var idevice = LibiMobileDevice.Instance.iDevice;
var lockdown = LibiMobileDevice.Instance.Lockdown;
var ret = idevice.idevice_get_device_list(out udids, ref count);
if (ret == iDeviceError.NoDevice)
{
// Not actually an error in our case
return;
}
ret.ThrowOnError();
// Get the device name
foreach (var udid in udids)
{
iDeviceHandle deviceHandle;
idevice.idevice_new(out deviceHandle, udid).ThrowOnError();
LockdownClientHandle lockdownHandle;
lockdown.lockdownd_client_new_with_handshake(deviceHandle, out lockdownHandle, "Quamotion").ThrowOnError();
string deviceName;
lockdown.lockdownd_get_device_name(lockdownHandle, out deviceName).ThrowOnError();
deviceHandle.Dispose();
lockdownHandle.Dispose();
}

Processing + Arduino + Serial port + Cp5.listbox

I would like to create a "listbox" (using the controlP5 GUI library) containing the serial port list: the goal is to create a stand alone app using Processing to communicate with Arduino Uno, independently from which OS I'm going to use (win, mac or linux), and select (with the "listbox") the correct Serial Port to communicate with Arduino.
is it possible??
ControlP5 cp5 = new ControlP5(this);
ListBox listBox = cp5.addListBox("serialPorts");
Serial serial;
String[] ports = Serial.list();
for (int i=0; i<ports.length; i++) {
listBox.addItem(ports[i]);
}
void controlEvent(ControlEvent theEvent) {
if(theEvent.isGroup() && theEvent.name().equals("myList")){
int val = (int)theEvent.group().value();
serial = new Serial(this, ports[val], 9600);
}
}
untested, but that's the basic idea...

Resources