How to read float variable from serial port (processing + arduino)
in
Integration and Hardware
•
2 months ago
plz help me :(
PROCESSING CODE
import processing.serial.*;
Serial port;
PFont text;
int h=401;
int num;
float mapa,x,y;
void setup(){
smooth();
size(500,500);
rectMode(CORNER);
text = loadFont("Chiller-Regular-48.vlw");
textFont(text);
textSize(40);
port = new Serial(this,Serial.list()[1],9600);
}
void draw(){
background(0);
fill(#E5E3DE);
rect(30,50,60,401);
ellipse(150,60,25,25);
ellipse(190,60,25,25);
ellipse(230,60,25,25);
if(keyPressed){
if(keyCode == DOWN){
if(h >= -1 && h <= 400){
h++; }}}
if(keyPressed){
if(keyCode == UP){
if( h >=0 && h <= 402 ){
h--;}}}
fill(#09CBD3);
mapa = map(h,401,-1,255,0);
port.write(mapa);
colores();
posicion();
if(keyPressed){
if ( keyCode == LEFT){
num = 1;
port.write(num);
}
if( keyCode == RIGHT){
num = 2;
port.write(num);
}
}
sentido(num);
for(int i =440 ;i >=0;i-=10){
line(43,i,80,i);
}
}
void posicion() {
if(mapa >= 127.5){
y = map (mapa,255,0,250,150);
x = map (mapa,255,0,350,150);
}
else {
y = map(mapa,127.5,0,200,250);
x = map(mapa,127.5,0,250,150);
}
fill(#FF0DB7);
line(250,250,x,y);
strokeWeight(5);
}
void colores() {
if(h >250 && h <=401){
fill(#FC0000);
arc(250,250,200,200,radians(180),radians(360));
text("Speed(pwm): " + mapa ,150,450);
rect(30,50,60,h);
ellipse(150,60,25,25);
fill(255);
ellipse(190,60,25,25);
fill(255);
ellipse(230,60,25,25);
}
if(h <=251 && h >=118){
fill(255);
ellipse(150,60,25,25);
fill(#FFE603);
arc(250,250,200,200,radians(180),radians(360));
text("Speed(pwm): " + mapa ,150,450);
rect(30,50,60,h);
ellipse(190,60,25,25);
fill(255);
ellipse(230,60,25,25);
}
if( h < 118 && h >=-1){
fill(255);
ellipse(150,60,25,25);
fill(255);
ellipse(190,60,25,25);
fill(#64FC00);
arc(250,250,200,200,radians(180),radians(360));
text("Speed(pwm): " + mapa ,150,450);
rect(30,50,60,h);
ellipse(230,60,25,25);
}}
void sentido(int x) {
if(x == 1) {
fill(#189093);
rect(160,300,190,50);
line(220,325,250,300);
line(220,325,245,349);
line(220,325,283,324);
}
else if ( x == 2 ){
fill(#0F3DF0);
rect(160,300,190,50);
line(283,324,261,300);
line(283,324,266,349);
line(220,325,283,324);
}
}
ARDUINO CODE:
int led = 3;
int val = 0;
void setup () {
Serial.begin(9600);
pinMode(led,OUTPUT);
}
void loop () {
while(Serial.available() == 0 );
val = Serial.read() - '0';
analogWrite(led,val);
}
1