There was an idea for a warm-up to make a project, the essence of which is as follows - I accept a couple of numbers (a and b) and number c. Depending on the values ​​of c, a and b are added together (if c = 0) Or they are subtracted if c = 1 The problem is that the sketch does not accept values ​​and does not calculate. In any case, does not produce a result. Please help with advice and analysis. I attach the code

void setup() { // put your setup code here, to run once: Serial.begin(9600); Serial.println("I'm ready"); Serial.println("Input a,b and operation"); Serial.println("Code operation"); Serial.println(" 0 - get summary"); Serial.println(" 1 - get negative"); } int k; int a,b,c; void loop() { // put your main code here, to run repeatedly: a = Serial.read(); b =Serial.read(); c = Serial.read(); if (c==0) { Serial.print("Result= "); Serial.println(a+b); } if (c==1) { Serial.print("Result= "); Serial.println(ab); } Serial.println("end loop"); } 

    1 answer 1

     //#Ulin Project void setup() { Serial.begin(9600); Serial.println("INIT OK"); } void loop() { while(Serial.read() != '~'); while(Serial.available() < 3); //command on byte i0 = (byte)Serial.read(); byte i1 = (byte)Serial.read(); byte i2 = (byte)Serial.read(); if(i0 == '1')Serial.println("0-OK"); else Serial.println("0-?"); if(i1 == '1')Serial.println("1-OK"); else Serial.println("1-?"); if(i2 == '1')Serial.println("2-OK"); else Serial.println("2-?"); int symma = byteToInt(i0)+byteToInt(i1)+byteToInt(i2); Serial.print("+:"); Serial.println(symma); } int byteToInt(byte a){ if(a == '0')return 0; if(a == '1')return 1; if(a == '2')return 2; if(a == '3')return 3; if(a == '4')return 4; if(a == '5')return 5; if(a == '6')return 6; if(a == '7')return 7; if(a == '8')return 8; if(a == '9')return 9; return 0; } 

    !!! Input must start with ~. For stability.

    Test0:

    Enter:

     ~101 

    Conclusion:

     INIT OK 0-OK 1-? 2-OK +:2 

    Test2:

    Enter:

    ~999

    Conclusion:

     0-? 1-? 2-? +:27 

    Test Online: https://www.tinkercad.com/things/4miWjU1NSi8-smooth-jarv-blorr

    I have provided a simple example of how to compare the bytes that come from the Serial, wrote a small protocol, which in the case of ~ 111 Returns 3 ok. He also wrote an example of adding numbers by casting from a byte to an int.

    • This is C ++. int byteToInt (char ch) {return ch-'0 '; } - Vanyamba Electronics
    • Look, I described the function below. The function is simple. as it compares just bytes .. and ascoding. - Denis Kotlyarov