I used this simple code to understand the basics of serial communication. This achieves simple communication between the computer and arduino:
String receive_buffer;
void setup() {
Serial.begin(9600);
}
void loop() {
if(Serial.available()>0) //check for any data received
{
receive_buffer = Serial.readString(); //read received data
Serial.print("received data is: ");
Serial.println(receive_buffer); //display received data
}
}
This works. Now, my next idea was to try communicating between two arduinos. I used this code for the reciever arduino.
The sender arduino contains a motor fitted with an encoder, and using the ppr value I calculate the rpm of the motor. The code for rpm works perfectly. I now want to communicate this data to the receiver.
Wiring: (RX,TX) of sender connected to (TX,RX) of receiver, and GND
is made common.
Now, on arduino.cc, it says that Serial.write() can have String as an input. So, I tried typecasting the rpm value (which was int), into a String, and then send that string to the receiver through Serial.write().
float ppr=512.0;
int encpin=3;
volatile long pulsecount=0;
float revs;
float rps;
int rpm;
extern volatile unsigned long timer0_millis;
void setup()
{
pinMode(encpin,INPUT_PULLUP);
Serial.begin(9600);
attachInterrupt(digitalPinToInterrupt(encpin),function,RISING);
//when pulse is detected
//interrupt triggered,
//function callled
}
//increments pulse by one
void function(){
pulsecount+=1;
}
void loop()
{
revs= pulsecount/ppr ;
if(millis()>=1000)
{
rps= revs;
rpm=rps*60;
pulsecount=0; //resets pulsecount
String strrpm= (String)rpm;
//Serial.println(rpm);
Serial.write(strrpm);
// Serial.println("string rpm");
//Serial.println(strrpm);
noInterrupts (); //resests millis() to 0
timer0_millis = 0;
interrupts ();
}
}
However, I get an error:
43:24: error: no matching function for call to 'HardwareSerial::write(String&)'
The issue is not with typecasting. I tried to simply print strrpm and it worked fine. When tried Serial.write() with a different and simple string, i.e Serial.write("abcdef");
, it still gave the same error.
How then should I should I send my strrpm (string rpm) value to the receiver?