Hello!
i tried to take a value from light sensor that connect to arduino uno and i succed to do it and turn on a LED.
after i tried to take the value to processing sketch that show if it is "light" or "dark"
but i always get a wrong value
here is the codes
i would like if someone halp me to find my mistake
arduino
int ledpin=9;
void setup() {
pinMode(ledpin,OUTPUT);
Serial.begin(9600);
}
void loop() {
int sensorValue = analogRead(A0);
if(sensorValue>600)analogWrite(ledpin,0);
if((sensorValue<490)&&(sensorValue>350))analogWrite(ledpin,50);
if(sensorValue<350)analogWrite(ledpin,255);
Serial.println(sensorValue);
}
processing
import processing.serial.*;
Serial port;
String bool="";
int index=0;
PFont font;
void setup()
{
size(500,500);
port=new Serial(this,"COM4",9600);
font = loadFont("AgencyFB-Bold-200.vlw");
textFont(font,200);
}
void draw()
{
background(0,0,index);
fill(46,209,2);
text(bool,80,175);
fill(200, 100,0);
//to check if index have the corent value
text(index,80,400);
}
void serialEvent (Serial port)
{index=port.read();
if(index<=450)
{
bool="dark";
}
if(index>450)
{
bool="light";
}}
i change the sensor value to 3 and send it to the serial
the procesing give me a unstable number
afther i add a delay of 500ms to arduino and the processing give me a 10 but in a few second is move to a very fast 3 or 50 and back to 10
thanks for repaly
I'd need to see your code, to be sure, but it looks like you are now sending '3',, and . Those are 51, 10, and 13 in the ASCII table.
Your Processing code needs to read the whole string of data being sent, not one character at a time. Use the bufferUntil() method the the Serial class, in setup() to define when the serialEvent() callback is to be called.
Then, use readStringUntil() in serialEvent(). Then, use String::trim() to get rid of the and . Then, convert the String instance to an int.
So, if sensorValue is between 350 and 490 (that if statement is backwards) send a 1. If it is less than 350, send a 1. If it is greater than 600, send a 0. If it is between 490 and 600, forget it. Do nothing.
What you are setting the LED pin to and what you are sending to the serial port are not consistent.