Answer the question
In order to leave comments, you need to log in
Absurd execution of conditional statements 3 times in Arduino nanov3, how to fix?
the first line comes out at startup, the 2nd line when I enter a number, and where do the other 3 come from? according to the logic of the program, in general, only 1 time should enter if because I equalize these 2 variables (xBase and xBase0) and in all cases this happens when I use Serial and Software Serial (via bluetooth) the same thing, and also strictly 3 times (2 extra times)
the code is here
const int baza = 5;
const int col = 6;
const int emi = A5;
int xBaza = 0;
int xCol = 255;
//int xEmi = 0;
int xBaza0 = 0;
void setup() {
Serial.begin(9600);
pinMode(baza, OUTPUT);
pinMode(col, OUTPUT);
}
void loop() {
analogWrite(col, xCol);
xBaza = Serial.read();
if(xBaza != xBaza0) {
xBaza0 = xBaza;
analogWrite(baza, xBaza);
writes();
}
}
void writes(void) {
Serial.print(analogRead(emi));
Serial.write(" baza: ");
Serial.print(xBaza);
Serial.write(" colector: ");
Serial.print(xCol);
Serial.write('\n');
}
Answer the question
In order to leave comments, you need to log in
void loop() {
analogWrite(col, xCol);
xBaza = Serial.read();
if(xBaza != xBaza0) {
xBaza0 = xBaza;
analogWrite(baza, xBaza);
writes();
}
}
if(xBaza != xBaza0 && xBaza != -1) {
First of all, you need to make sure that you get what you expect from the port in the sketch. That is, what you "enter" in the port monitor. To do this, comment out your entire if for now, and instead, immediately after the line xBaza = Serial.read(); print the xBaza value to the port monitor. Everything should become clear.
https://www.arduino.cc/en/Serial/Read
Or rather the paragraph
Returns
the first byte of incoming serial data available (or -1 if no data is available) - the int
read() method returns the read data, if any and -1 if there is no data.
Change the code to the following
void loop() {
analogWrite(col, xCol);
xBaza = Serial.read();
if(xBaza >= 0 && xBaza != xBaza0) {
xBaza0 = xBaza;
analogWrite(baza, xBaza);
writes();
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question