i have made ultrasonic rader using arduino uno and processing tool. now i have to make it wireless with the help of xbee. i am not geting how to make it.as i have never work on xbee.plz help me its urgent.
i want to use xbee in my project along with processing tool???
Kinect-Processing-Arduino Serial Communication problem.
Hi!
For my master finals I am planning to make some kind of interactive sculptures. One of them is supposed to work with the kinect sensor using the body movements to manipulate the sculpture. I have been trying some examples that I found in some books and I found one in particular that could be adapted to my work. The example I am trying to use is from the chapter 6 in the book "Arduino & Kinect Projects" from Enrique Ramos Melgar and Ciriaco Castro Diez. ( http://www.slideshare.net/lujomiOtakuShairen/arduino-and-kinect-projects-42068493 )
It is a puppet that can be manipulated via internet with the kinect sensor through Processing sending signal to the servos attached to each joint in the Arduino.
My idea is to make it to do the same but over serial communication and not over a server/client. That the user stands in front of the sculpture and the servos move with their body movement in front of them without using internet but just normal serial communication between Kinect-Processing-Arduino.
Could any of you help me with this?
Here I show you the codes from the book that I have where the processing code is not yet talking to the server and according to the book I could use this code and connect it via serial communication to the arduino to move the servos with the body movement read by the kinect. https://www.dropbox.com/sh/b9r3a09yvzlbrbj/AACmdyeHgKV_zhhrLcyYT-9_a?dl=0
I am sorry if Im not that clear, I am doing my best and I would be very happy if some of you could give me a hint of how to achieve this in order to adapt the example to my own project.
Thanx in advance!
Kinect processing serial to arduino problem firmmata
Hi , im doing a project using kinect and arduino and i use firmmata. My problem is the arduino suddenly stop working . i think because of synching issue.
This is my code
import SimpleOpenNI.*;
> import processing.serial.*;
> import cc.arduino.*;
>
> SimpleOpenNI context;
> Arduino arduino;
> int pin =8;
> int pin_motor =9;
> int pos=90;
>
> float PI = 3.14159265;
> int id=100;
> PVector torso = new PVector();
> float angle;
>
> //check bit if gesture is ddetected
> int check =0;
>
> void setup()
> {
> // instantiate a new context
> context = new SimpleOpenNI(this);
>
> // enable depthMap generation
> context.enableDepth();
>
> // enable skeleton generation for all joints
> context.enableUser();
>
> background(200,0,0);
> stroke(0,0,255);
> strokeWeight(3);
> smooth();
>
> // create a window the size of the depth information
> size(context.depthWidth(), context.depthHeight());
>
> arduino = new Arduino (this,Arduino.list()[0],57600);
> arduino.pinMode(pin, Arduino.SERVO);
> arduino.pinMode(pin_motor, Arduino.SERVO);
> arduino.servoWrite(pin,90);
> Setpoint=0;
> SetControllerDirection(DIRECT);
> SetMode(AUTOMATIC);
> SetSampleTime(30);
> SetOutputLimits(-90, 90);
> SetTunings(1.2, 0, 0.2);
> for (int i =90; i<93; i++)
> {
> arduino.servoWrite(pin,i);
> delay (200);
> }
>
> }
>
> void draw()
> {
> // update the camera
> context.update();
> // draw depth image
> image(context.depthImage(),0,0);
> IntVector userList = new IntVector();
> context.getUsers(userList);
> // check if the skeleton is being tracked
>
> for (int i=0; i<userList.size(); i++)
> {
> int userId = userList.get(i);
>
> if (context.isTrackingSkeleton(userId))
> {
> drawSkeleton(userId);
> float handDistance = getJointDistance(userId, SimpleOpenNI.SKEL_LEFT_HAND,SimpleOpenNI.SKEL_RIGHT_HAND);
> PVector position = new PVector();
> if (id != 100)
> {
> context.getJointPositionSkeleton(id, SimpleOpenNI.SKEL_TORSO, torso);
> Input = atan2(torso.x,torso.z) * 180/PI;
> Compute();
> arduino.servoWrite(pin,(int)(pos+Output));
> context.getCoM(id,position);
> context.convertRealWorldToProjective(position,position);
> fill(0,255,0);
> textSize(80);
> text(id,position.x,position.y);
> arduino.servoWrite(pin_motor,92);
> }
> else
> {
> context.getCoM(userId,position);
> context.convertRealWorldToProjective(position,position);
> fill(255,0,0);
> textSize(40);
> text(userId,position.x,position.y);
> arduino.servoWrite(pin_motor, 90);
> }
> }
> }
>
> }
>
> // draw the skeleton with the selected joints
> void drawSkeleton(int userId)
> {
> // draw limbs
> context.drawLimb(userId, SimpleOpenNI.SKEL_HEAD, SimpleOpenNI.SKEL_NECK);
>
> context.drawLimb(userId, SimpleOpenNI.SKEL_NECK, SimpleOpenNI.SKEL_LEFT_SHOULDER);
> context.drawLimb(userId, SimpleOpenNI.SKEL_LEFT_SHOULDER, SimpleOpenNI.SKEL_LEFT_ELBOW);
> context.drawLimb(userId, SimpleOpenNI.SKEL_LEFT_ELBOW, SimpleOpenNI.SKEL_LEFT_HAND);
>
> context.drawLimb(userId, SimpleOpenNI.SKEL_NECK, SimpleOpenNI.SKEL_RIGHT_SHOULDER);
> context.drawLimb(userId, SimpleOpenNI.SKEL_RIGHT_SHOULDER, SimpleOpenNI.SKEL_RIGHT_ELBOW);
> context.drawLimb(userId, SimpleOpenNI.SKEL_RIGHT_ELBOW, SimpleOpenNI.SKEL_RIGHT_HAND);
>
> context.drawLimb(userId, SimpleOpenNI.SKEL_LEFT_SHOULDER, SimpleOpenNI.SKEL_TORSO);
> context.drawLimb(userId, SimpleOpenNI.SKEL_RIGHT_SHOULDER, SimpleOpenNI.SKEL_TORSO);
>
> context.drawLimb(userId, SimpleOpenNI.SKEL_TORSO, SimpleOpenNI.SKEL_LEFT_HIP);
> context.drawLimb(userId, SimpleOpenNI.SKEL_LEFT_HIP, SimpleOpenNI.SKEL_LEFT_KNEE);
> context.drawLimb(userId, SimpleOpenNI.SKEL_LEFT_KNEE, SimpleOpenNI.SKEL_LEFT_FOOT);
>
> context.drawLimb(userId, SimpleOpenNI.SKEL_TORSO, SimpleOpenNI.SKEL_RIGHT_HIP);
> context.drawLimb(userId, SimpleOpenNI.SKEL_RIGHT_HIP, SimpleOpenNI.SKEL_RIGHT_KNEE);
> context.drawLimb(userId, SimpleOpenNI.SKEL_RIGHT_KNEE, SimpleOpenNI.SKEL_RIGHT_FOOT);
> }
>
> // Event-based Methods
>
> // when a person ('user') enters the field of view
> void onNewUser(SimpleOpenNI curContext,int userId)
> {
> println("onNewUser - userId: " + userId);
> println("\tstart tracking skeleton");
>
> context.startTrackingSkeleton(userId);
> }
>
> void onLostUser(SimpleOpenNI curContext,int userId)
> {
> println("onLostUser - userId: " + userId);
> if (userId == id)
> {
> id =100;
> check=0;
> }
> }
>
> void onVisibleUser(SimpleOpenNI curContext,int userId)
> {
> //println("onVisibleUser - userId: " + userId);
> }
>
>
>
> // prints out the distance between any two joints
> float getJointDistance(int userId,int joint1Id,int joint2Id)
> {
> float d; // to store final distance value
>
> // two PVectors to hold the position of two joints
> PVector joint1 = new PVector();
> PVector joint2 = new PVector();
>
> // get 3D position of both joints
> context.getJointPositionSkeleton(userId,joint1Id,joint1);
> context.getJointPositionSkeleton(userId,joint2Id,joint2);
>
> d = distance3D(joint1,joint2); // calcualte the distance between the two joints
> if ((d<300) && (check==0))
> {
> id =userId;
> check=1;
> }
> return d;
> }
>
> // calculate the distance between any two points in 3D space and return it as a float
> float distance3D(PVector point1, PVector point2)
> {
> float diff_x, diff_y, diff_z; // to store differences along x, y and z axes
> float distance; // to store final distance value
>
> // calculate the difference between the two points
> diff_x = point1.x - point2.x;
> diff_y = point1.y - point2.y;
> diff_z = point1.z - point2.z;
>
> // calculate the Euclidean distance between the two points
> distance = sqrt(pow(diff_x,2)+pow(diff_y,2)+pow(diff_z,2));
>
> return distance; // return the distance as a float
> }
>
> //PID
>
> /*working variables*/
> float lastTime;
> double Input, Output, Setpoint;
> double ITerm, lastInput;
> double kp, ki, kd;
> long SampleTime = 1000;
> double outMin, outMax;
> boolean inAuto = false;
>
> int MANUAL =0;
> int AUTOMATIC = 1;
> int DIRECT =0;
> int REVERSE= 1;
>
> int controllerDirection = DIRECT;
>
> void Compute()
> {
> /*How long since we last calculated*/
> if(!inAuto) return;
> long now = millis();
> int timeChange = int(now - lastTime);
>
> if(timeChange>=SampleTime)
> {
> /*Compute all the working error variables*/
> double error = Setpoint - Input;
> ITerm += (ki * error);
> if(ITerm> outMax) ITerm= outMax;
> else if(ITerm< outMin) ITerm= outMin;
> double dInput = (Input - lastInput);
>
> /*Compute PID Output*/
> Output = kp * error + ITerm - kd * dInput;
> if(Output > outMax) Output = outMax;
> else if(Output < outMin) Output = outMin;
> /*Remember some variables for next time*/
> lastInput = Input;
> lastTime = now;
> }
> }
>
> void SetTunings(double Kp, double Ki, double Kd)
> {
> if (Kp<0 || Ki<0|| Kd<0) return;
> double SampleTimeInSec = ((double)SampleTime)/1000;
> kp = Kp;
> ki = Ki * SampleTimeInSec;
> kd = Kd / SampleTimeInSec;
>
> if(controllerDirection ==REVERSE)
> {
> kp = (0 - kp);
> ki = (0 - ki);
> kd = (0 - kd);
> }
> }
>
> void SetSampleTime(int NewSampleTime)
> {
> if (NewSampleTime > 0)
> {
> double ratio = (double)NewSampleTime
> / (double)SampleTime;
> ki *= ratio;
> kd /= ratio;
> SampleTime = (long)NewSampleTime;
> }
> }
>
> void SetOutputLimits(double Min, double Max)
> {
> if(Min > Max) return;
> outMin = Min;
> outMax = Max;
>
> if(Output > outMax) Output = outMax;
> else if(Output < outMin) Output = outMin;
>
> if(ITerm> outMax) ITerm= outMax;
> else if(ITerm< outMin) ITerm= outMin;
> }
>
> void SetMode(int Mode)
> {
> boolean newAuto = (Mode == AUTOMATIC);
> if(newAuto && !inAuto)
> { /*we just went from manual to auto*/
> Initialize();
> }
> inAuto = newAuto;
> }
>
> void Initialize()
> {
> lastInput = Input;
> ITerm = Output;
> if(ITerm> outMax) ITerm= outMax;
> else if(ITerm< outMin) ITerm= outMin;
> }
>
> void SetControllerDirection(int Direction)
> {
> controllerDirection = Direction;
> }
Question about sending strings to firmata from processing
Hey guys,
Doing a school project and got stuck on using both serial.write to send a string value while using firmata at the same time. Is there any way to send a string value using firmata without serial.write?
Here is a part of my code: (In setup())
arduino = new Arduino(this, Arduino.list()[6], 57600);
String portName = Serial.list()[6];
myPort = new Serial(this, portName, 57600);
Based on a condition, I want to send this to Arduino from Processing (In draw())
myPort.write('H');
Was searching google for an answer but can't seem to find it. Help please! Thanks!
Attached is the error I get. The code is able to run but I get that error.
Motor not running
I am using controlP5 on processing to make a GUI that runs a dc motor on Arduino. The GUI asks for the velocity, time for the motor to run, and the direction and stores them in variables. When the start button is hit it is suppose to send the data to the Arduino. The problem is that the motor is not running. I put some println commands in the processing code to figure out where it stops but all the println commands work. I don't know if it is a problem with the Arduino code or if it is not sending the data.
Processing Code
import processing.serial.*;
import controlP5.*;
Serial myPort;
ControlP5 cp5;
DropdownList serialPortsList;
Serial serialPort;
final int BAUD_RATE=9600;
ControlTimer c;
Textlabel t;
Textlabel txtlblwhichcom;
Textarea commTextarea;
ListBox commListbox;
Serial[] myPorts=new Serial[1];
int col=color(255);
int segment=4;
String val[];
long current;
long previous;
long timePassed;
String timeMillis;
PrintWriter output;
String photo;
String [] var=new String[4];
String vel;
String time="0";
int timeMeasure;
String dir;
String onOff="0";
int onOffMeasure;
String fileName;
String fileN;
String textValue="";
boolean firstContact=false;
RadioButton rb;
void setup(){
myPort=new Serial(this, Serial.list()[3], 9600);
myPort.bufferUntil('\n');
size(700,500);
PFont font=createFont("arial", 20);
String[] portNames=Serial.list();
cp5=new ControlP5(this);
serialPortsList=cp5.addDropdownList("Serial ports").setPosition(10,10).setWidth(200);
for(int i=0;i<portNames.length;i++) serialPortsList.addItem(portNames[i],i);
c=new ControlTimer();
t=new Textlabel(cp5,"--",100,100);
c.setSpeedOfTime(1);
cp5.addCheckBox("checkBox")
.setPosition(250, 330)
//.setColorBackground(color(255,13,227))
.setColorForeground(color(120))
.setColorActive(color(255))
.setColorLabel(color(255))
.setSize(40, 40)
.setItemsPerRow(3)
.setSpacingColumn(100)
.setSpacingRow(20)
.addItem("Photogate 1", 0)
.addItem("Photogate 2", 50);
cp5.addTextfield("Belt Velocity (mm/s)")
.setPosition(20,90)
.setSize(200,40)
.setFont(font)
.setFocus(true)
.setColor(color(255,0,0))
;
cp5.addTextfield("Run Time (s)")
.setPosition(20,160)
.setSize(200,40)
.setFont(font)
.setFocus(false)
.setColor(color(255,0,0))
;
cp5.addTextfield("Text File Name")
.setPosition(20,230)
.setSize(200,40)
.setFont(font)
.setFocus(false)
.setColor(color(255,0,0))
;
cp5.addButton("Enter")
.setValue(0)
.setPosition(240,90)
.setSize(80,40)
.getCaptionLabel().align(ControlP5.CENTER, ControlP5.CENTER)
;
cp5.addButton("ENTER")
.setValue(0)
.setPosition(240,160)
.setSize(80,40)
.getCaptionLabel().align(ControlP5.CENTER, ControlP5.CENTER)
;
cp5.addButton("EnteR")
.setValue(0)
.setPosition(240,230)
.setSize(80,40)
.getCaptionLabel().align(ControlP5.CENTER, ControlP5.CENTER)
;
cp5.addButton("Start")
.setValue(0)
.setPosition(120,410)
.setSize(80,40)
.setColorBackground(color(9,158,12))
.setColorLabel(color(0,0,0))
.getCaptionLabel().align(ControlP5.CENTER, ControlP5.CENTER)
;
cp5.addButton("Stop")
.setValue(0)
.setPosition(480,410)
.setSize(80,40)
.setColorBackground(color(168,8,8))
.setColorLabel(color(0,0,0))
.getCaptionLabel().align(ControlP5.CENTER, ControlP5.CENTER)
;
rb = cp5.addRadioButton("radioButton")
.setPosition(480,100)
.setSize(90,40)
.setColorForeground(color(120))
.setColorActive(color(255))
.setColorLabel(color(255))
.setItemsPerRow(1)
.setSpacingColumn(50)
.addItem("Clockwise",1)
.addItem("Counter-ClockWise",2)
;
textFont(font);
}
void draw(){
current=millis();
background(0);
fill(255);
t.setValue(c.toString());
t.draw(this);
t.setPosition(480,50);
if(segment==0){
var[0]=vel;
var[1]=time;
var[2]=dir;
var[3]=onOff;
timeMeasure=Integer.parseInt(time);
onOffMeasure=Integer.parseInt(time);
println("segment 1 end");
segment=1;
}
else if(segment==1){
for(int x=0;x<4;x++){
myPort.write(var[x]);
print("sent ");
println(var[x]);
}
segment=2;
previous=current;
output=createWriter(fileName);
println("wrote file");
}
else if(segment==2){
if(myPort.available()>0){
photo=myPort.readStringUntil('\n');
output.print(photo);
timePassed=current-previous;
timeMillis=str(timePassed);
output.println(timeMillis);
}
if((current-previous)>=(timeMeasure*1000)){
segment=3;
onOff="0";
println("segment 2 finished");
}
}
else if(segment==3){
var[0]="0";
var[1]="0";
var[2]="0";
var[3]=onOff;
for(int x=0;x<4;x++){
myPort.write(var[x]);
}
output.flush();
output.close();
segment=4;
println("segment 3 finished");
}
else{
segment=4;
//println("fish");
}
}
public void Enter(){
vel=cp5.get(Textfield.class,"Belt Velocity (mm/s)").getText();
println("Got Velocity");
}
public void ENTER(){
time=cp5.get(Textfield.class,"Run Time (s)").getText();
println("Got Time");
}
public void EnteR(){
fileN=cp5.get(Textfield.class,"Text File Name").getText();
fileName=fileN+".txt";
println("Got filename");
}
void radioButton(int a) {
dir=str(a);
println("a radio Button event: "+a);
}
public void Start(){
/*if(mousePressed){
segment=0;
println("Mouse Working");
}*/
if(current>100){
println("if statement Working");
segment=0;
onOff="1";
}
}
public void Stop(){
if(current>100){
segment=3;
onOff="0";
}
}
void controlEvent(ControlEvent theEvent){
if(theEvent.isGroup()){
if(serialPort !=null){
serialPort.stop();
serialPort=null;
}
String portName=serialPortsList.getItem((int)theEvent.getValue()).getName();
try{
serialPort=new Serial(this,portName,BAUD_RATE);
}
catch(Exception e){
}
}
}
Arduino Code
#include <Wire.h>
#include <stdlib.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_PWMServoDriver.h"
Adafruit_MotorShield AFMS=Adafruit_MotorShield();
Adafruit_DCMotor *myMotor=AFMS.getMotor(3);
unsigned long Timems=0;
unsigned long Timeus=0;
int Photogate1=HIGH;
int Photogate2=HIGH;
int PhotogatePin1=10;
int PhotogatePin2=12;
int motorPin=3;
float onOff=0;
float var[4];
int index=0;
float volt;
float direct;
long previous;
float vel;
float time;
void setup(){
Serial.begin(9600);
AFMS.begin();
pinMode(motorPin, OUTPUT);
}
void loop(){
unsigned long current=millis();
if(onOff==0){
if (Serial.available()){
float incomingValue=Serial.parseFloat();
var[index]=incomingValue;
index++;
}
if(var[3]==1){
onOff=var[3];
previous=current;
}
}
else if(onOff==1){
vel=var[0];
time=var[1]*1000;
direct=var[2];
volt=vel;
index=0;
if(direct==1){
myMotor->run(FORWARD);
}
if(direct==2){
myMotor->run(BACKWARD);
}
onOff=2;
}
else if(onOff==2){
myMotor->setSpeed(volt);
/* Photogate1=digitalRead(PhotogatePin1);
Photogate2=digitalRead(PhotogatePin2);
if(Photogate1==LOW){
Timems=millis();
Timeus=micros();
Serial.println("Photogate 1");
delay(100);
}
else if(Photogate2==LOW){
Timems=millis();
Timeus=micros();
Serial.println("Photogate 2");
delay(100);
}
else{
digitalWrite(Photogate1, HIGH);
digitalWrite(Photogate2, HIGH);
}
} */
if(Serial.available()){
float incomingValue=Serial.parseFloat();
var[index]=incomingValue;
index++;
}
if(var[3]==0){
onOff=3;
}
}
else{
vel=var[0];
time=var[1]*1000;
direct=var[2];
onOff=var[3];
volt=vel;
index=0;
}
}
Processing and Arduino connection - whats wrong?
Hello! i use my Arduino to send over serial - messages like "Fail=1." "Fail=2." or "Otvet=1" etc.
i use code
` void serialEvent(Serial port) {
String input = port.readStringUntil('.');
if (input != null) { // Print message received println(input);
if (input.equals("Otvet=1")==true)
{
println("OTVET 1");
// fill(0, 255, 0);
// ellipse(56, 46, 55, 55);
}
if (input.equals("Fail=1")==true)
{
println("FAILSTART=1");
// fill(255, 0, 0);
// ellipse(500, 500, 55, 55);
}
}
} `
and - IF working ONLY one time - if first message from Arduino is "Otvet=1." and next is "Fail=1." - i see first "OTVET 1" in console but after this i dont see FAILSTART=1...
What i do wrong?
Thanks. Sorry my bad English
Send Data from Arduino to Processing over serial // help please
I am trying to send data from an Arduino Uno to Processing.
I made a simple sketch which does this no problem. It is only when I try to have the Arduino send data to Procesing in an "if conditional" from an analog sensor reading that I run into trouble.
For instance, the simple send from Arduino looks like this:
int ledPin = 13;
void setup()
{
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop()
{
Serial.write(1);
digitalWrite(ledPin, HIGH);
delay(200);
Serial.write(0);
digitalWrite(ledPin, LOW);
delay(200);
}
And the corresponding Processing code looks like this:
import processing.serial.*;
Serial myPort; // Create object from Serial class
int val;
void setup() {
//change the 0 to a 1 or 2 etc. to match your port
String portName = Serial.list()[2];
myPort = new Serial(this, portName, 9600);
rectMode(CENTER);
}
void draw()
{
background(0);
fill(255);
if (myPort.available()>0)
{
val = myPort.read();
}
println(val);
if (val == 1) {
rect(width/2, height/2, 30, 30);
}
}
It makes a white square appears when the number "1" is sent to Processing. It works so simple. It works every time. I was so pleased.
However, when I try it with the next Arduino sketch, nothing ever happens. It always stays on "0" even though I can see on the Arduino the LED turns on showing that yes, this piece of code has run. The Processing portion can stay exactly the same.
Why am I not seeing it work right? I have tried so many things. This tells me it's either painfully obvious or I've done something horribly karmically wrong and this is my punishment.
Thank you for nay tips.
// Used to interface with electronic drum pads
// Using a piezo sensor
// Casey Scalf 2015
int ledPin = 13;
int padPin = 0; // Red
// Black is Ground
byte val;
byte a = 0;
int THRESHOLD = 20;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop() {
val = analogRead(padPin);
if (val <= THRESHOLD) {
digitalWrite(ledPin, LOW);
a = 0;
Serial.write(a);
}
if (val >= THRESHOLD) {
digitalWrite(ledPin, HIGH);
a = 1;
Serial.write(a);
}
}
Arduino serial comms weirdness
I don't know if this is an arduino issue or processing issue, so I'm starting in this forum.
You can think of my project as a weather station. It's not a weather station, but you can still visualize it that way. I have an Arduino Mega with three or four analog sensors that are displayed using Processing on a Win7 PC via serial communication. A very straight forward project configuration.
I would like Processing to request data from the Arduino, rather than the Arduino just sending data at some constant rate, but have discovered I can request data from the processing side only once per second. The Arduino doesn't want to read incoming requests faster than that no matter what "read" strategy I employ (read, readbytesuntil, serialevent, etc) on the Arduino side. I don't need super fast performance, just looking for 5-10 serial transfers per second.
Interestingly, if I pull the serial.write (to request data from the arduino) out of the draw() function and put it into a mouseClicked() function...I can use the mouse to send many requests per second and that works perfectly. The Arduino responds to each serial.write() and I'm easily sending 7-8 per second by just clicking the mouse button very quickly. So this appears to be an issue surrounding the draw() function.
Whether I use delay() or framerate() to throttle processing execution, processing to arduino serial seems to be limited to once per second requests. Data size is small in both cases. Processing is only sending a one byte command and new line to the Arduino. The Arduino is responding with about 96 bytes of data. Serial speed doesn't matter, I have tried 9600 - 115200 and the results are the same. I've also tested both Uno and Mega with the same results.
Any ideas? Anyone willing to test the code below to see what your results are? Just change the delay values in either script.
// ARDUINO CODE
char cin;
void setup()
{
Serial.begin(115200);
}
void loop()
{
char din[4];
if ( (Serial.available()) > 0 ) {
Serial.readBytesUntil('\n',din,4);
if ( din[0] == 'M' ) {
Serial.println(din[0]);
Serial.flush();
}
}
delay(100);
}
// PROCESSING CODE
import processing.serial.*;
Serial myPort;
char c;
int i=0;
void setup()
{
size(200,200);
String portName = Serial.list()[0];
myPort = new Serial(this,portName,115200);
}
void draw()
{
if ( myPort.available() > 0 ) {
i++;
c = myPort.readChar();
println(c + " " + i);
}
myPort.write("M\n");
delay(1000);
}
NPE(NullPointerException)
in processing 2.2.1:
import com.temboo.core.*;
import com.temboo.Library.Yahoo.Weather.*;
import processing.serial.*;
Serial port;
int temperature;
// Create a session using your Temboo account application details
TembooSession session = new TembooSession("user", "app", "hash");
void setup() {
runGetTemperatureChoreo();
port = new Serial(this, "COM3", 9600);
}
void runGetTemperatureChoreo() {
GetTemperature getTemperatureChoreo = new GetTemperature(session);
getTemperatureChoreo.setAddress("novorossiysk");
GetTemperatureResultSet getTemperatureResults = getTemperatureChoreo.run();
temperature=int(getTemperatureResults.getTemperature());
temperature = (temperature-32)*5/9;
println(temperature);
println(Serial.list()[1]);
if(temperature==27){
println(port.available());
while (port.available() == 0) {
delay(300);
port.write(65);
}
}
}
After that code i got: 27 (temperature - it`s okay, i convert F to C =) ) And i get error NullPointerException. Arduino is okay, in loop:
if (Serial.available()){ // If data is available to read,
val = Serial.read();
Serial.write(val);
}
can not understand that the hell, now over 3 hours of night, i want to sleep.
How to Attach two more Servo motors to Kinect Skeleton?
Hi! I am trying to solve this little problem with an example from the book "Making things see" where with the use of Kinect Processing and Arduino you can control two servo motors by moving your left arm. The kinect through the Skeleton App reads the movement of the joints on your arm. It works perfectly with one side but now I would like to add the right arm with other two servo motors. There is definitely something that I am not understanding because I have tried copying the code and replacing it with for example "SimpleOpenNI.SKEL_LEFT_ELBOW, SimpleOpenNI.SKEL_LEFT_HAND, SimpleOpenNI.SKEL_LEFT_SHOULDER" and so on and nothing changes. It might not be as easy as I thought. I am struggling with this that's why I decided to ask it here to see if someone could help me with a hint.
Here I post the Processing code and after the Arduino code.
Thanks in advance for your help!
import SimpleOpenNI.*;
SimpleOpenNI kinect;
import processing.serial.*;
Serial port;
void setup() {
size(640, 480);
kinect = new SimpleOpenNI(this);
kinect.enableDepth();
kinect.enableUser(SimpleOpenNI.SKEL_PROFILE_ALL);
kinect.setMirror(true);
println(Serial.list());
String portName = Serial.list()[8];
port = new Serial(this, portName, 9600);
}
void draw() {
kinect.update();
PImage depth = kinect.depthImage();
image(depth, 0, 0);
IntVector userList = new IntVector();
kinect.getUsers(userList);
if (userList.size() > 0) {
int userId = userList.get(0);
if ( kinect.isTrackingSkeleton(userId)) {
// get the positions of the three joints of our arm
PVector rightHand = new PVector();
kinect.getJointPositionSkeleton(userId,
SimpleOpenNI.SKEL_RIGHT_HAND,
rightHand);
PVector rightElbow = new PVector();
kinect.getJointPositionSkeleton(userId,
SimpleOpenNI.SKEL_RIGHT_ELBOW,
rightElbow);
PVector rightShoulder = new PVector();
kinect.getJointPositionSkeleton(userId,
SimpleOpenNI.SKEL_RIGHT_SHOULDER,
rightShoulder);
// we need right hip to orient the shoulder angle
PVector rightHip = new PVector();
kinect.getJointPositionSkeleton(userId,
SimpleOpenNI.SKEL_RIGHT_HIP,
rightHip);
// reduce our joint vectors to two dimensions
PVector rightHand2D = new PVector(rightHand.x, rightHand.y);
PVector rightElbow2D = new PVector(rightElbow.x, rightElbow.y);
PVector rightShoulder2D = new PVector(rightShoulder.x,
rightShoulder.y);
PVector rightHip2D = new PVector(rightHip.x, rightHip.y);
// calculate the axes against which we want to measure our angles
PVector torsoOrientation =
PVector.sub(rightShoulder2D, rightHip2D);
PVector upperArmOrientation =
PVector.sub(rightElbow2D, rightShoulder2D);
// calculate the angles between our joints
float shoulderAngle = angleOf(rightElbow2D,
rightShoulder2D,
torsoOrientation);
float elbowAngle = angleOf(rightHand2D,
rightElbow2D,
upperArmOrientation);
// show the angles on the screen for debugging
fill(255,0,0);
scale(3);
text("shoulder: " + int(shoulderAngle) + "\n" +
" elbow: " + int(elbowAngle), 20, 20);
byte out[] = new byte[2];
out[0] = byte(shoulderAngle);
out[1] = byte(elbowAngle);
port.write(out);
}
} }
float angleOf(PVector one, PVector two, PVector axis) {
PVector limb = PVector.sub(two, one);
return degrees(PVector.angleBetween(limb, axis));
}
// user-tracking callbacks!
void onNewUser(int userId) {
println("start pose detection");
kinect.startPoseDetection("Psi", userId);
}
void onEndCalibration(int userId, boolean successful) {
if (successful) {
println(" User calibrated !!!");
kinect.startTrackingSkeleton(userId);
}
else {
println(" Failed to calibrate user !!!");
kinect.startPoseDetection("Psi", userId);
} }
void onStartPose(String pose, int userId) {
println("Started pose for user");
kinect.stopPoseDetection(userId);
kinect.requestCalibrationSkeleton(userId, true);
}
Arduino code
#include <Servo.h>
// declare both servos
Servo shoulder;
Servo elbow;
// setup the array of servo positions
int nextServo = 0;
int servoAngles[] = {0,0};
void setup() {
// attach servos to their pins
shoulder.attach(9);
elbow.attach(10);
Serial.begin(9600);
}
void loop() {
if(Serial.available()){
int servoAngle = Serial.read();
servoAngles[nextServo] = servoAngle;
nextServo++;
if(nextServo > 1){
nextServo = 0;
}
shoulder.write(servoAngles[0]);
elbow.write(servoAngles[1]);
} }
Problem with data processing.
Hello! Guys, please help me! I'm in desperation!
I have a problem with data processing in Processing and vibration feedback in my prototype.
From the beginning: I made a simple device using a Mega326p processor which should be O.K., for instance with Arduino. I added bluetooth BLUEFRUIT EZ-LINK and a simple vibration motor, like the one on the bottom.
http://learningaboutelectronics.com/images/Vibration-motor-circuit.png
In Processing I wrote a simple program to control one object, and with one obstacle present. For example :We have two ellipses - one of them we have to move form one place to another without touching the other (the obstacle/s). If You make a mistake, you should feel vibrations. And everything is OK if I have just one obstacle. When I am adding more objects/obstacles, vibration feedback is completely useless. It gets jammed, the response is delayed, pulse width modulation is nonexistent in this situation ( which I wanted to measure in three versions :/ ).
If You have ANY IDEA how I can fix this, I will be really greatful.
Thanks!
P.S. I am a beginner in programming, so I am pretty sure that there is better way to write this program. For instance, program with a few objects:
import processing.serial.*;
Serial myPort;
int blueX = 1287;
int blueY = 655;
float blackX, blackY;
int AX, AY;
int BX, BY;
int CX, CY;
int DX, DY;
int EX, EY;
int FX, FY;
int GX, GY;
int HX, HY;
float blueSize = 30;
float blackSize = 40;
int ASize = 50;
int BSize = 30;
int CSize = 75;
int DSize = 75;
int ESize = 120;
int FSize = 75;
int GSize = 27;
int HSize = 75;
color bluecolor;
color blueActive;
color blackcolor;
color Acolor;
color Bcolor;
color Ccolor;
color Dcolor;
color Ecolor;
color Fcolor;
color Gcolor;
color Hcolor;
color colorActiveObstacle;
boolean Overblue = false;
boolean Overblack = false;
boolean OverA = false;
boolean OverB = false;
boolean OverC = false;
boolean OverD = false;
boolean OverE = false;
boolean OverF = false;
boolean OverG = false;
boolean OverH = false;
void setup()
{
String portName = Serial.list()[0];
myPort = new Serial(this, portName, 9600);
size(500, 500);
bluecolor = color(#0000FF);
blueActive = color(#CC00FF);
blackcolor = color(000000);
colorActiveObstacle = color(34);
Acolor = color(225);
Bcolor = color(225);
Ccolor = color(225);
Dcolor = color(225);
Ecolor = color(225);
Fcolor = color(225);
Gcolor = color(225);
Hcolor = color(225);
blackX = 20;
blackY = 20;
blueX = 450;
blueY = 450;
AX = 200;
AY = 40;
BX = 320;
BY = 60;
CX = 430;
CY = 150;
DX = 300;
DY = 80;
EX = 250;
EY = 180;
FX = 100;
FY = 100;
GX = 1240;
GY = 130;
HX = 300;
HY = 500;
}
void draw()
{
background(78);
if(mousePressed)
{
fill(blueActive);
blueX = mouseX;
blueY = mouseY;
// myPort.write('H');
} else {
fill(bluecolor);
myPort.write('L');
}
ellipse(blueX, blueY, blueSize, blueSize);
fill(blackcolor);
ellipse(blackX, blackY, blackSize, blackSize);
if(overA(AX,AY, ASize))
{
fill(Acolor);
//fill(colorActiveObstacle);
myPort.write('H');
} else {
fill(Acolor);
myPort.write('L');
}
ellipse(AX, AY, ASize, ASize);
if(overB(BX,BY, BSize))
{
fill(Bcolor);
//fill(colorActiveObstacle);
myPort.write('H');
} else {
myPort.write('L');
fill(Bcolor);
}
ellipse(BX, BY, BSize, BSize);
if(overC(CX,CY, CSize))
{
fill(Ccolor);
//fill(colorActiveObstacle);
myPort.write('H');
} else {
myPort.write('L');
fill(Ccolor);
}
ellipse(CX, CY, CSize, CSize);
if(overD(DX,DY, DSize))
{
fill(Dcolor);
//fill(colorActiveObstacle);
myPort.write('H');
} else {
myPort.write('L');
fill(Dcolor);
}
ellipse(DX, DY, DSize, DSize);
if(overE(EX,EY, ESize))
{
fill(Ecolor);
// fill(colorActiveObstacle);
myPort.write('H');
} else {
myPort.write('L');
fill(Ecolor);
}
ellipse(EX, EY, ESize, ESize);
if(overF(FX,FY, FSize))
{
fill(Fcolor);
//fill(colorActiveObstacle);
myPort.write('H');
} else {
myPort.write('L');
fill(Fcolor);
}
ellipse(FX, FY, FSize, FSize);
if(overG(GX,GY, GSize))
{
fill(Gcolor);
//fill(colorActiveObstacle);
myPort.write('H');
} else {
fill(Gcolor);
myPort.write('L');
fill(Gcolor);
}
ellipse(GX, GY, GSize, GSize);
if(overH(HX,HY, HSize))
{
fill(Gcolor);
myPort.write('H');
} else {
myPort.write('L');
fill(Hcolor);
}
ellipse(HX, HY, HSize, HSize);
}
boolean overA(int x, int y, int diameter) {
float disX = x - mouseX;
float disY = y - mouseY;
if (sqrt(sq(disX) + sq(disY)) < 60) {
return true;
} else {
return false;
}
}
boolean overB(int x, int y, int diameter) {
float disX = x - mouseX;
float disY = y - mouseY;
if (sqrt(sq(disX) + sq(disY)) < 50) {
return true;
} else {
return false;
}
}
boolean overC(int x, int y, int diameter) {
float disX = x - mouseX;
float disY = y - mouseY;
if (sqrt(sq(disX) + sq(disY)) < 73) {
return true;
} else {
return false;
}
}
boolean overD(int x, int y, int diameter) {
float disX = x - mouseX;
float disY = y - mouseY;
if (sqrt(sq(disX) + sq(disY)) < 73) {
return true;
} else {
return false;
}
}
boolean overE(int x, int y, int diameter) {
float disX = x - mouseX;
float disY = y - mouseY;
if (sqrt(sq(disX) + sq(disY)) < 95) {
return true;
} else {
return false;
}
}
boolean overF(int x, int y, int diameter) {
float disX = x - mouseX;
float disY = y - mouseY;
if (sqrt(sq(disX) + sq(disY)) < 73) {
return true;
} else {
return false;
}
}
boolean overG(int x, int y, int diameter) {
float disX = x - mouseX;
float disY = y - mouseY;
if (sqrt(sq(disX) + sq(disY)) < 50) {
return true;
} else {
return false;
}
}
boolean overH(int x, int y, int diameter) {
float disX = x - mouseX;
float disY = y - mouseY;
if (sqrt(sq(disX) + sq(disY)) < 73) {
return true;
} else {
return false;
}
}
photosensor triggers sound, how do I stop the sound from looping?
Hello! I'm writing a code for a Lilypad and one of the inputs I'm hoping to use is a photosensor, which should trigger a sound when the sensor is covered. That bit is all working fine, but the sound is looped and I can't figure out how to stop that? I tried noLoop()
but that just plays the sound when the Lilypad is first connected, and nothing happens when the sensor is covered.. This is my code:
import processing.serial.*;
import cc.arduino.*;
import ddf.minim.*;
Minim minim;
Event event_example;
Arduino arduino;
int input_example, led; //the led just gives additional feedback if the the sensor was covered
void setup() {
size(470, 280);
println(Arduino.list());
arduino = new Arduino(this, Arduino.list()[0], 57600);
input_example = 2; //this is the pin the photo resistor is connected to
led = 6; //this is the pin that the led is connected to
arduino.pinMode(input_example, Arduino.INPUT);
minim = new Minim(this);
event_example= new Event("audio/example.wav");
}
void draw() {
if (arduino.analogRead(input_example) < 500) {
event_example.trigger();
arduino.digitalWrite(led, Arduino.HIGH);
} else {
event_example.stop();
arduino.digitalWrite(led, Arduino.LOW);
}
}
//The following code is in another tab
public class Event {
boolean flag;
AudioSample sample;
public Event (String file) {
sample = minim.loadSample(file, 512);
flag = false;
}
void trigger() {
sample.trigger();
flag = true;
}
void stop() {
flag = false;
}
}
Any help is much appreciated!!
Creating a Class with Firmata for Arduino
I'm creating a radar simulation, and want to send data from Processing to an Arduino to control 4 small stepper motors to display range and bearing on 4 dials. Firmata seems like a good solution for this.
Would like to create a Class "MOTOR" and instantiate each of the motors in the main sketch. I've successfully created a number of simple classes before, but am unclear on how/where to place the special libraries that need to be imported for Firmata. Also not sure where this should be placed:
arduino = new Arduino(this, Arduino.list()[5], 115200);
The general question is: When creating a Class which uses specific libraries - where should the libraries be imported - in the 'main' sketch or in the class?
USB (com port list)
Hi all,
I'm working on a project with arduino and lately i got interested in processing too looks as a nice interface programming software which I'd like to use, so let's get to the main question. I'm totally new to processing so take it easy with me :D I saw some tutorials how to connect arduino with processing thru com port but I need to set my exact arduino com port and sometimes the com port changed depending on what computer i sit.
****Question: ****
- Is there a way to get a drop menu with the available PC com ports and chose which one i need? It's not hard to change just a number in the code but i wanna make a drop down list with the available com ports so in this way i would not go and mess with the code every time picking ports.
data of books
Howdy, I do have a considerable measure of preparing books, however arrive any handling books on 3D Visualization? I don't see numerous books/instructional exercises separated from 'Imagining information' from Ben fry(2007) and a couple stuff on openprocessing. If you don't mind share any/all assets/instructional exercises/and so on particularly for 3d information perception! Much obliged
Help with serials and strings
Hi Processing Forum,
I am in the process of hacking a rotary phone, using Arduino and Processing to convert the phone into a recording and playback device. It is a really interesting project and I have made some progress, but I got stuck on a string from the serial port. My code is long, so I will share my public gist here: https://gist.github.com/lizzybrooks/b88531b906860d4fc4af.
Here is the function that seems to be giving me trouble:
void readNumbers(){
if ( myPort.available() > 0)
{
// get the value from the serial port
do{
val = myPort.readStringUntil('\n'); // read it and store it in val
} while (val == null);
// print every value received to the console so we know what we got
// println(val);
// println(val.length());
if (val.equals("6\r\n")){
println("hooray. you work. let's play a different audio file");
// anything else and its input from the phone
// so do whatever you want if you receive input from the phone here...
}
}
If you have any ideas or can help me with syntax, I would so much appreciate it. I am a beginner coder working on a complicated project, but I am eager to learn.
Thanks so much!
Lizzy
degree symbol
I have an arduino webserver and a processing client. I want arduino to send a degree celsius or just the degree symbol. I have tried client.println("\u0b00"); I do get a degree symbol. but there is Á in front of the degree symbol.
How can I let the arduino send the symbol without any other symbols?
Please Help.. Basic template of RADAR..
Hello guys.. i am new to processing IDE. I have a code of a basic Radar spotting template. when using Arduino IDE i can see the values coming back from sensor using serial print. But in processing this code is not drawing the objects detected in a range. Please help what changes i have to make. in this code.. i got this code from website..
import processing.serial.*; Serial port; Serial port2; String data = ""; String Radius = ""; String Theta = ""; int index = 0; float distance = 0; float angle = 0; float pi = 22.0/7; void setup() { size(1000,1000); background(255,255,255); ellipse(500,500,1000,1000); line(500,0,500,1000); line(0,500,1000,500); line(500,500,1000,0); line(500,500,0,0); port = new Serial(this, "COM3", 9600); port.bufferUntil('.'); } void draw() { } void serialEvent(Serial port) { data = port.readStringUntil('.'); data = data.substring(0, data.length() - 1); index = data.indexOf(","); Radius = data.substring(0, index); Theta = data.substring (index+1 , data.length()); translate(500,500); point (0,0); distance = float(Radius); angle = float(Theta) /180 * pi; fill(30,200,30); ellipse(distance * cos(angle) , -1 * distance * sin(angle) , 5,5); }
Any suggestions is worth a gold... Thank you
Problems with Split
Hi:
I'm trying to communicate arduino and processing using serial, but when i send a string and then i try to split it in processing is doesn't works. I want to split this string:
DEL:0.0229999995#ACC:2.12,9.87,0.00#GYR:-0.03,-0.12,-0.03#FIL:1.98,9.20,-0.03#MAG:0.00
Using '#' as delimiter to obtain this: DEL:0.0229999995
ACC:2.12,9.87,0.00
GYR:-0.03,-0.12,-0.03
FIL:1.98,9.20,-0.03
MAG:0.00
But split function only removes the '#' and it returns this:
DEL:0.0250000000ACC:2.15,9.55,0.00GYR:633.60,-664.19,-647.42FIL:2.03,9.63,-647.42MAG:0.00
Code: void dataDecode(String data){
try { // Parse the data
String[] dataStrings = split(data,'#'); for (int i = 0; i < dataStrings.length; i++) print(dataStrings[i]);
/*
How to light up 8 led with a TLC5940NT and the arduino ?
Hello everyone,
I am bussy with a project for myself. I want to make wings on my back and on the wings will come much leds.
I have bought a TLC5940NT because I was thinking I need that to light up so much leds. But I really don't understand how the TLC5940NT works and what it does.
Now I spend a whole day looking on the internet to find a way to light up leds with TLC5940NT. But I really don't understand all the explainations.
Is there someone here whole can explain me very simpel how I use the TLC5940NT and how I light up led with that thing.
Thanks so much !!!!! Your all are my last hope