Sending numbers via Serialport from C # to Java

I am doing bluetooth quadcoopter using Arduino. I have no problem sending emails, but I cannot write or read numbers.

I'm not very good at programming, so bear with me.

C # code:

    private void button1_Click(object sender, EventArgs e)
        {
            int testInt = 35;
            byte[] testByte = BitConverter.GetBytes(testInt);
            serialPort1.Write(testByte, 0, 0);

            int i = BitConverter.ToInt32(testByte,0);
            label5.Text = i.ToString();
        }

      

Here I tried to convert to send a byte, at first I just sent it directly as a string. I am getting the same result both ways.

Arduino code:

 <code>void loop() 
{
  // put your main code here, to run repeatedly:
  if(Serial.available())
  {
    int data = Serial.read();
    if(data=='35')
     {
        digitalWrite(13, HIGH);
     }
  }
}

      

Why won't the LEDs light up? How do I read numbers from a serial port?

+3


source to share


1 answer


This sends one byte (0 to 255):

private void button1_Click(object sender, EventArgs e) {
    // set up to send only one byte
    byte[] testByte = {35};
    // send one byte
    serialPort1.Write(testByte, 0, 1);
}

      

And this receives and interprets it on the Arduino:

void loop() {
    if (Serial.available()) {
        byte data = Serial.read();
        if (data == 35) {
            digitalWrite(13, HIGH);
        }
    }
}

      



If you think you can send a number greater than 255, it might be just as easy to send a string. Add a new line character to the end of the line:

String testString = "35\n";

      

and use a new line to let Arduino know that you have done submitting the code, something like this:

#define MAX_SIZE 5;
char button[MAX_SIZE+1];

if (Serial.available()) {
    int bytesRead = Serial.readBytesUntil ('\n', button, MAX_SIZE);
    if (bytesRead > 0) {
        button[bytesRead] = '\0';
        int result = atoi(button);
        if (result == 35) {
            digitalWrite(13, HIGH);
        } else {
            digitalWrite(13, LOW);
        }
    }
}

      

0


source







All Articles