我可以用C#通过串行端口发送int吗?
我可以用C#通过串行端口发送int吗 A用C语言开发了一个应用程序,通过串口为arduino发送数据。这个数据是一个comand,它可以是一个int!不是一根绳子! 我该怎么做?我读了一些字节,但a不在S下我可以用C#通过串行端口发送int吗?,c#,serial-port,arduino,C#,Serial Port,Arduino,我可以用C#通过串行端口发送int吗 A用C语言开发了一个应用程序,通过串口为arduino发送数据。这个数据是一个comand,它可以是一个int!不是一根绳子! 我该怎么做?我读了一些字节,但a不在S下 using System; using System.Windows.Forms; // using System.Threading; using System.IO; using System.IO.Ports; pulic class senddata(){ private voi
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代码:
#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);
}
}
}
#包括
无效设置()
{
伺服。连接(9);
Serial.begin(9600);
pinMode(13,输出);
}
void循环()
{
if(Serial.available())
{
int cmd=(无符号字符)Serial.read();
如果(cmd==91){
数字写入(13,高);
}
}
}
您可以使用其他重载方法:()
//数字应为小于256的正值
整数=20;
字节[]缓冲区=新字节[]{Convert.ToByte(number)};
serialPort.Write(缓冲区,0,1);
这将从缓冲区中写入单字节。要写入值为
1的4字节整数,需要先将其转换为字节数组。
我用位转换器
来实现这一点。您还可以使用Convert.ToByte
,如@sll所示。
请注意,指定要发送到串行端口的字节数非常重要。
4字节整数?2字节?单个字节?
你似乎没有在你的问题中具体说明这一点
int MyInt = 1;
byte[] b = BitConverter.GetBytes(MyInt);
serialPort1.Write(b,0,4);
这将写入一个32位整数,但代码需要一个8位整数(C中的字符)。@FredVaz:你应该开始接受问题的答案。请勾选你最喜欢的答案旁边的“复选标记”。@Guffa:正如我所说的,我在问题中没有看到任何东西说明他想要单字节还是4字节整数。但是变化很小。@abelenky:如果它实际上是一个多字节的值,那么您还需要知道它是采用小端还是大端格式。8位整数=一个字节??那么为什么不创建一个一字节的数组并写入它呢???
int MyInt = 1;
byte[] b = BitConverter.GetBytes(MyInt);
serialPort1.Write(b,0,4);