I would read this as a byte instead of an int, as only 1 byte of data actually comes in.
int cm = Serial.read();
You then create a new instance of cm here
long cm;
which will likely = 0 and wipe out the read you just did. serial.println and see.
I would take it out.
Then cm = 0 is <100,
you analogWrite it (and analogWrite only needs a byte, 0 to 255)
(100 - 0) *10 = 1000
so I don't know what that will actually do for an output.
The line
long cm
creates a new variable called cm and sets it to zero.
Therefore when you do the if statement next it will always be less than 100 and so the buzzer will always sound.
Also, how is B getting its serial data?
From the serial monitor?
That data will come in as type char, you will need to convert it to an byte www.ascitable.com
Simple way is just to subtract '0' (or 48, or 0x30);
byte cm = Serial.read() - '0';
If you are receiving multiple characters, 125
then you have to read three times, and convert those:
if (Serial.available()>2){ // at least 3 bytes received?
byte upper = Serial.read() - '0';
byte middle = Serial.read() - '0';
byte lower = Serial.read() - '0;
byte total = upper * 100 + middle * 10 + lower; // don' enter more than 255 for analogWrite!
I just make all the variables global, declare them all before setup(), and skip all this constant declaration nonsense.
I think it has something to do with the cm code. Is there other code aside from cm ? I received a data from A by reading from serial monitor. But for some reason, my buzzer keep sounding in every way.