簡體   English   中英

如何從C#設置為Arduino的int

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

我正在一個項目中使用arduino和C#根據溫度控制風扇,這里的問題是我需要一個選項供用戶提供風扇打開時的輸入溫度。 我為此使用C#和arduino uno,並且設法在C#界面中顯示溫度值,但是當我嘗試發送int時,該值未達到arduino。

我一直在研究,已經看到將int轉換為字節可以解決此問題,但是我不知道這是如何工作的以及如何將其放入代碼中。

這是該特定按鈕的C#代碼:

這里應該從文本框中獲取值並將其轉換為字節。

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);
            }
        }

這是我的arduino代碼:

在這里,變量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);


}

我認為,最簡單的方法(可確保您也獲得出色而穩定的性能)是將CmdMessenger庫用於Arduino / C#通信。 您可以非常簡單地集成和修改庫和示例 還有一個整數圖的示例。 我希望這可以幫助你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM