简体   繁体   English

如何从C#设置为Arduino的int

[英]How to set an int to arduino from c#

I'm working in a project to control a fan depending on the temperature using arduino and C#, the catch here is that I need an option for the user to provide input temperature in which the fan will turn on. 我正在一个项目中使用arduino和C#根据温度控制风扇,这里的问题是我需要一个选项供用户提供风扇打开时的输入温度。 I am using C# and an arduino uno for this and i have manage to show the temperature value in the C# interface but when i try to send the int, the value doesnt reach the arduino. 我为此使用C#和arduino uno,并且设法在C#界面中显示温度值,但是当我尝试发送int时,该值未达到arduino。

I have been investigating and have seen that turning the int into bytes will fix the problem but I don't understand how this works and how to put this in the code. 我一直在研究,已经看到将int转换为字节可以解决此问题,但是我不知道这是如何工作的以及如何将其放入代码中。

Here is my C# Code for that specific button: 这是该特定按钮的C#代码:

Here is supposed to grab the value from the textbox and convert it to bytes. 这里应该从文本框中获取值并将其转换为字节。

private void cmdSend_Click(object sender, EventArgs e)
        {
            if(SP.IsOpen)
            {
                int temp = Int32.Parse(txttemp.Text);
                byte[] b = BitConverter.GetBytes(temp);
                SP.Write(b,0,4);
            }
        }

And here is my arduino code: 这是我的arduino代码:

Here the variable T is supposed to be the one to receive the value from C# and change the Max temp in which the fan will turn on. 在这里,变量T应该是从C#接收值并更改风扇将打开的最高温度的变量。

float temperatura = 0; //variable for the temperature
int fan = 8; //pin of the fan
int T;

void setup(){

 Serial.begin (9600); //inicia comunicacion serial

 pinMode(fan,OUTPUT);//configuracion del pin 8
}

void loop(){
//Calcula la temperatura usando como referencia 5v
temperatura = (5.0 * analogRead(0)*100.0)/1023.0;
Serial.println (temperatura); //writes temperature in the serial
delay (500);

//esto enciende y apaga el ventlador
if (temperatura < T){//change the number to the range you desire
  digitalWrite(fan, LOW);

}else
  digitalWrite(8,HIGH);


}

I think the easiest way, which ensures you also a great and stable performance, is the usage of the CmdMessenger library for the Arduino / C# communication. 我认为,最简单的方法(可确保您也获得出色而稳定的性能)是将CmdMessenger库用于Arduino / C#通信。 You can integrate and modify the library and the examples very simple. 您可以非常简单地集成和修改库和示例 There is also an example of an integer plot. 还有一个整数图的示例。 I hope this helps you. 我希望这可以帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM