Can I send an int using serialPort in C #?

Is it possible to send an int using serialPort in C #?

A has developed a C # application that sends data to a serial port for arduino. This data is a command that can be int! Not a line! How can i do this? I read a few bytes, but I do not understand.

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. } } 

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); } } } 
+4
source share
3 answers

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

Please note that it is very important to specify how many bytes you want to send to the serial port.
4 byte int? 2 bytes? one byte?
It seems you did not indicate this in your question.

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

You can use another 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 one byte from the buffer.

+2
source

Just as it may be.

Use .NET Shell for Arduino

https://github.com/d3n4/Zelectro Wrapper for .NET

https://github.com/d3n4/ZelectroSketch Sketch for Arduino

Example:

 using System; using System.Threading; using Zelectro; namespace ZelectroDemo { public class Test3Program : ArduinoProgram { private LED led; public override void setup() { led = new LED(Pin.PWM11); } public override void loop() { led.Blink(50); } } } 
0
source

Source: https://habr.com/ru/post/1383349/


All Articles