-2

im sending the value 1500 from another MCU with

 fdserial_txChar(transmit, send >> 7);    // send Higher 7 bits
 fdserial_txChar(transmit, send & 0x7F);  // send Lower 7 bits

and was receiving it with code that looked like this

servo1  = fdserial_rxChar(receive) << 7;    // get Higher 7 bits
servo1 += fdserial_rxChar(receive) & 0x7F;  // get and add Lower 7 bits

how do i rewrite the receiving code so arduino will compile it?

Thank you.

here is the code im trying to get working

void setup() {
// physical pin 2=TX 3=RX  
  Serial.begin(9600);
  pinMode(3, OUTPUT);      // set LED pin as output
  digitalWrite(3, LOW);    // switch off LED pin
}

void loop() {

if (Serial.available()) { // char data_rcvd = Serial.read(); // read one byte from serial buffer and save to data_rcvd

int data_rcvd = Serial.read() &lt;&lt; 7;     //get Higher 7 bits
int data_rcvd += Serial.read() &amp; 0x7F;  //get and add Lower 7 bits




if (data_rcvd == 1500) digitalWrite(3, HIGH); // switch LED On
if (data_rcvd == '0') digitalWrite(3, LOW);  // switch LED Off

}

// if (digitalRead(8) == HIGH) Serial.write('0'); // send the char '0' to serial if button is not pressed. // else Serial.write('1'); // send the char '1' to serial if button is pressed.

}

jsotola
  • 1,554
  • 2
  • 12
  • 20

2 Answers2

1

You have a few obvious problems here.


if (Serial.available()) {
 int data_rcvd = Serial.read() << 7;     //get Higher 7 bits
 int data_rcvd += Serial.read() & 0x7F;  //get and add Lower 7 bits

You are testing that one byte is available on the serial port and then reading two bytes. Too soon. Test for two bytes if you are planning to read two.


if (data_rcvd == '0') digitalWrite(3, LOW);  // switch LED Off

Why the quotes? Why not: if (data_rcvd == 0) ?


How are you intending to synchronize the sending and receiving?

Your sender is sending HLHLHLHL - what if the receiver starts while the low byte is being sent? You will receive LHLHLH which means your received data will be meaningless.

You are better off sending "readable" data, like "1500" rather than 1500, terminating with a newline, and structuring your receiving code to read until it hits a newline. That will synchronize the receiver (after the first reading, anyway).


For more tips about reading serial data see: How does serial communications work on the Arduino?

Also my post about serial data on my forum has code for buffering incoming serial data and waiting for a newline.

Nick Gammon
  • 38,901
  • 13
  • 69
  • 125
1

the answer to my question of how to write

servo1  = fdserial_rxChar(receive) << 7;    // get Higher 7 bits
servo1 += fdserial_rxChar(receive) & 0x7F;  // get and add Lower 7 bits

so Arduino would compile it is....

combined = (val1 << 7) | (val2);
sempaiscuba
  • 1,042
  • 9
  • 21
  • 32