FredVaz
FredVaz

Reputation: 533

Can I send a int by serialPort in C#?

Can I send a int by serialPort in C# ?

A developed a app in C# that send a data by serial port for arduino. This data is a comand that just can be a int ! Not a String ! How can i do this ? I read something bytes but a don´t undertsand.

using System;
using System.Windows.Forms;
//
using System.Threading;
using System.IO;
using System.IO.Ports;

pulic class senddata(){

private void Form1_Load(object sender, System.EventArgs e)
{
//Define a Porta Serial
    serialPort1.PortName = textBox2.Text;
    serialPort1.BaudRate = 9600;
    serialPort1.Open();
}
private void button1_Click(object sender, System.EventArgs e)
{
     serialPort1.Write("1");  // "1" is a string, but i put 1 (int) give me a error.       
}

}

The arduino code:

#include <Servo.h>

void setup()
{
    servo.attach(9);
    Serial.begin(9600);
    pinMode(13, OUTPUT);
}

void loop()
{
    if(Serial.available())
    {

      int cmd = (unsigned char)Serial.read();

      if(cmd == 91){
        digitalWrite(13,HIGH);
      }
    }
}

Upvotes: 4

Views: 21630

Answers (2)

sll
sll

Reputation: 62514

You can use an other overload method: (MSDN)

public void Write(
    byte[] buffer,
    int offset,
    int count
)
// number should be positive value less than 256
int number = 20;
byte[] buffer = new byte[] { Convert.ToByte(number) };
serialPort.Write(buffer, 0, 1);

This will write out single byte from a buffer

Upvotes: 2

abelenky
abelenky

Reputation: 64682

To write a 4-byte integer, with value 1, you need to convert it to a a byte-array first.
I do this with BitConverter. You can also do it with Convert.ToByte, as shown by @sll.

Note that it is very important to specify how many bytes you want to send to the serial port.
A 4-byte int? 2-bytes? a single byte?
It doesn't seem that you specified that in your question.

int MyInt = 1;

byte[] b = BitConverter.GetBytes(MyInt);
serialPort1.Write(b,0,4);

Upvotes: 4

Related Questions