i need help about my small project i have arduino and im reading integer values via serial port to control LED so im getting trouble if i insert any value via serial monitor LED turns on, i want to control LED according to conditions in the code. i want to read integer value in the serial monitor and control the led according to a value received via serial port.
heres my codes
int All;
int LEDpin =13;
Void Setup()
{
PinMode(LEDPin,OUTPUT);
}
Void Loop()
{
While( Serial,Available()==0)
All=Serial.intParse();
if (All=1)
{
digitalWrite(LEDpin,HIGH);
}
if (All=0)
{
digitalWrite(LEDpin,LOW);
}
if (All=2)
{
digitalWrite(LEDpin,HIGH);
delay(1000);
digitalWrite(LEDpin,LOW);
}
}
you set your variable All
in your code instead of checking it against a value:
instead of:
if(All=1){
...
}
you should write:
if(All == 1){
...
}
edit:
And you should take a look at the naming convention:
void
instead of Void
all
instead of All
Your code has a lot of things to fix. First of all what @Tom Mekken pointed out you make comparisons with ==
, not =
. Then you access members with .
instead of ,
. And you should read until available
is greater than zero, not equal to. And the setup
and loop
functions are NOT Setup
and Loop
, like PinMode
and While
and Void
(C is case sensitive). And you should initialize the serial communication with the baud rate. And LEDPin
is not LEDpin
. And intParse
is not ParseInt
.
And... Indent it properly. Here is your code fixed:
int All;
int LEDpin = 13;
void setup()
{
Serial.begin(9600);
pinMode(LEDpin, OUTPUT);
}
void loop()
{
while( Serial.available() > 0)
All = Serial.parseInt();
if (All == 1)
{
digitalWrite(LEDpin,HIGH);
}
if (All == 0)
{
digitalWrite(LEDpin,LOW);
}
if (All == 2)
{
digitalWrite(LEDpin,HIGH);
delay(1000);
digitalWrite(LEDpin,LOW);
}
}
Now, that was just the core part. Your code, however, has also functional problems. Instead of a bunch of if I suggest you to use a switch. And instead of reading a whole integer, since your data is just single-digit, I suggest you to read just one char. This way you won't have problems with other chars and, moreover, you won't have problems when there are available non-printable chars.
Something like this should do the trick:
int LEDpin = 13;
void setup()
{
Serial.begin(9600);
pinMode(LEDpin, OUTPUT);
}
void loop()
{
switch (Serial.read())
{
case '1':
digitalWrite(LEDpin,HIGH);
break;
case '0':
digitalWrite(LEDpin,LOW);
break;
case '2':
digitalWrite(LEDpin,HIGH);
delay(1000);
digitalWrite(LEDpin,LOW);
break;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.