Click here to Skip to main content
15,891,923 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello good people.
I want to send data to controller, and then its will turn a "Light-emitting diode" On.
IM confused how to send bytes , as i get this command sending data on string format, not on bytes:
serialPort1.Write("1");

Maybe im wrong
Any Help, Thanks.
Code included below.

What I have tried:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Sending_data_serial
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            serialPort1.Open();
            serialPort1.Write("1");
            serialPort1.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            serialPort1.PortName = textBox1.Text;
            serialPort1.BaudRate = Convert.ToInt32(textBox2.Text);


        }
    }
}
Posted
Updated 26-Jan-17 21:44pm

You need to have a look at this overload of the function, SerialPort.Write Method (Byte[], Int32, Int32) (System.IO.Ports)[^], it allows you to write the bytes from a buffer. Pass 0 and byteArray.Length as the parameter to send a complete buffer to the serial port.

To send just one byte, you can do the following,
C#
// bytes is assumed to be of byte[] type with some data.
serialPort1.Write(bytes, 0, 1); // Start from 0, go to 1; 1 byte.

Another good example is given in solution by Jochen in Solution 2, also see that but you can get the bytes from any source, be that character encoding, command or whatever.
 
Share this answer
 
v2
Comments
JeezyWonder 26-Jan-17 21:42pm    
Thx for ur answer, Afzaal, can u please make a code example how to send 1 byte. Please, cuz i cant figure it out
Afzaal Ahmad Zeeshan 27-Jan-17 3:50am    
Kindly see the updated post.
You can still use the method accepting a string to send bytes because that uses ASCII encoding by default (converts each character to an ASCII byte value).

So the binary value 0x01 can be send as
C#
serialPort1.Write("\u0001");


But if you need to send data containing a null byte, values >= 128, or avoid the Unicode to ASCII conversion, you must use the method accepting a byte array:
C#
var dataByte = new byte[] { 0x00 };
serialPort1.Write(dataByte, 0, 1);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900