arduinointegerbytearduino-idenodemcu

arduino byte to integer without converting to decimal system


Hope you doing fine. I want you to help me out.

I had a nodemcu on my desk. and i thought it will feel lonely and connected an arduino to him with SoftwareSerial. Now, they both seem to have a good time but have a small issue...

I want arduino send 1s and 0s to nodemcu as integer (e.g 0101) and I want nodemcu to read it as 0101 as normal everyday integer number. But instead it thinks that it is in a binary system (while it looks like, it is not a byte) and converts it to a decimal one... And that ruins the whole relationship and delays my project...

How arduino sends:

    int g=d1*1000 + d2*100 + d3*10 + d4;
    ss.write((g));
    Serial.println(g);

g is an integer that should be sent to nodemcu because he is a good guy. but currently not acting very good.

How nodemcu recieves:

    if(ss.available()>2){
    int f=(int)ss.read();
    Serial.print("Look what arduino gave me :) ");
    Serial.println(f);
  
    sen1 = f/1000 %10;
    sen2 = (f/100)%10;
    sen3 = (f/10)%10;
    sen4 = f%10;
    }

The whole idea of using arduino, and not nodemcu alone is because arduino has couple of more pins than nodemcu. and while nodemcu is busy with transferring data, arduino can do some other stuff with other components.

Sorry for my childish question, I am just not leaving laboratory here in university and not leaving my home for a long time and haven't talked since... september, i guess...

Thank you for stopping by. Thanks in advance!


Solution

  • Since you are trying to send binary as text, I suggest a more practical approach:

    //  Sending:
    
    Serial.write(d1 ? '1' : '0'); // Insures the integrity of
    Serial.write(d2 ? '1' : '0'); // sent data. 
    Serial.write(d3 ? '1' : '0');
    Serial.write(d4 ? '1' : '0');
    

    You could receive the data in at least 2 ways, depending on what is more practical for you.

    As a single integer, in binary format, this will allow for the usual boolean testing, i.e: flag2 = recv & 0x02.

    int flags;
    if (ss.available >= 4)
    {
        flags = 0;
        for (int i = 0; i < 4; ++i)
            flags = (flags << 1) + (ss.read() != '0');
    
        d1 = flags & 0x08;  // for example...
        d2 = flags & 0x04;
        d3 = flags & 0x02;
        d4 = flags & 0x01;
    }
    

    As 4 different flags, this would match your input. It's almost the same code

    if (ss.available >= 4)
    {
        d1 = (ss.read() != '0');
        d2 = (ss.read() != '0');
        d3 = (ss.read() != '0');
        d4 = (ss.read() != '0');
    }
    

    Avoid divisions and modulo arithmetic operations when possible, they are the slowest arithmetic operations not only on Arduino, but on all CPUs. They are slower than other basic operations by a factor of around 20.