Unity3D+Arduino控制LED灯泡

翻墙看到的一个帖子。只要是代码,分享给大家

首先需要一个客户端就是Arduino的程序

 void setup() 
 {
   Serial.begin(9600);
 }
 
 void loop() {
 // int val = 2;
 int incomingByte=0;
 //Sending value
 // Serial.write(val);
 // delay(1000);
 
 //Receiving value
  if (Serial.available() > 0) {
         // read the incoming byte:
         incomingByte = Serial.read();
 
         // say what you got:
         Serial.print("I received: ");
                 Serial.println(incomingByte, DEC);
 
 }
 }
用arduino编译器新建一个程序,直接复制进去就可以了,简单解释一下:setup是启动函数,相当于unity的start函数,而loop函数相当于Update函数,setup函数中的
Serial.begin(9600);
我们将通过监听9600端口进行unity和arduino的通信

下面是unity的代码:

 using UnityEngine;
 using System.Collections;
 using System.IO.Ports;
 using System.Threading;
 
 public class SerialPortTest : MonoBehaviour 
 {
     //Setup parameters to connect to Arduino
     public static SerialPort sp = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
     public static string strIn;        
     public  string message;
	float ww=0;
     // Use this for initialization
     void Start () 
     {
     OpenConnection();
		InvokeRepeating("kk",1,2);
     }
 void kk(){
			sp.Write(ww.ToString());
			ww+=0.01f;
	}

     void Update()
     {
             //Read incoming data
      //   strIn = sp.ReadLine();
    // print(strIn);
 
            //You can also send data like this

       //     sp.Write("2");
 
 
     }
     
     //Function connecting to Arduino
     public void OpenConnection() 
     {
         if (sp != null) 
         {
             if (sp.IsOpen) 
             {
                 sp.Close();
                 message = "Closing port, because it was already open!";
             }
             else 
             {
                 sp.Open();  // opens the connection
                 sp.ReadTimeout = 50;  // sets the timeout value before reporting error
                 message = "Port Opened!";
             }
         }
         else 
         {
             if (sp.IsOpen)
             {
                 print("Port is already open");
             }
             else 
             {
                 print("Port == null");
             }
         }
     }
 
     void OnApplicationQuit() 
     {
         sp.Close();
     }
 }

为了测试,我使用了
InvokeRepeating("kk",1,2);函数,就是说,每个2秒调用一次kk()函数,这里面每次调用豆浆想端口里面写一条数据,并且数据是递增的,所以灯会一闪一闪越来越亮。
还有就是,buildsetting里面,API Compatibility level要修改为。NET2.0,不然会找不到端口



  • 5
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值