gpt4 book ai didi

c# - 从 C# 更改 for 循环中的 arduino 变量

转载 作者:太空狗 更新时间:2023-10-29 21:38:17 24 4
gpt4 key购买 nike

我有一个项目是通过 Arduino 使用 C# GUI 控制步进电机,我不知道如何更改 n C# 中文本框的 for 循环变量。例如,每当我想更改步进电机的角度时,我都会输入值 n

这是我的 Arduino 代码:

int i;
int n;
void setup() {
Serial.begin(9600);
pinMode(2,OUTPUT);
pinMode(9,OUTPUT);
pinMode(10,OUTPUT);
digitalWrite(9,HIGH);
delay(10);
}

int received = 0;
void loop() {
if (Serial.available() == 1) {
received = Serial.read();
switch (received) {
case 50: // Received ASCII 0
digitalWrite(2, HIGH);
break; //Move on
case 51: // Received ASCII 1
digitalWrite(2, LOW);
for(i=0; i<n;i++) {
delayMicroseconds(300);
digitalWrite(10, LOW);
delayMicroseconds(600);
digitalWrite(10, HIGH);
delayMicroseconds(300);
}
delay(1000);
break; //Move on
}
}
}

这是我的 C# 代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
namespace Serial_send {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e) {
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports) {
cbPORT.Items.Add(port);
}
}

private void button2_Click(object sender, EventArgs e) {
string n = tbgoc.Text.ToString();
string t = cbPORT.Text.ToString();
string s = tbDATA.Text.ToString();
serial(t, s);
}

void serial(string Port_name, string data_send) {
SerialPort sp = new SerialPort(Port_name, 9600);
sp.Open();
sp.Write(data_send);
sp.Close();
}
} //end form
} //end namespace

感谢您花时间提供帮助,抱歉我的英语不好。

问候

最佳答案

您只需要定义一个适当的命令约定来控制您的板。为了简单起见,我建议您始终按照以下约定发送 n 的值:

  • n=0:关闭电源
  • n>0:打开电源并使用 n 的值来执行您的操作

此外,使用 Serial.parseInt 代替按字符解析 Arduino 中接收到的数据。功能更强大。

parseInt() returns the first valid (long) integer number from the serial buffer. Characters that are not integers (or the minus sign) are skipped.

这是 Arduino 代码中修改后的循环函数:

void loop() {
if (Serial.available() == 1) {

//Read first int until the comma
received = Serial.parseInt();

if (received == 0) { //Power off
digitalWrite(2, HIGH);
} else { //Power on and set n
n = received;
digitalWrite(2, LOW);
for(i=0; i<n;i++) {
delayMicroseconds(300);
digitalWrite(10, LOW);
delayMicroseconds(600);
digitalWrite(10, HIGH);
delayMicroseconds(300);
}
delay(1000);
}
}
}

这是修改后的 C# 代码:

private void button2_Click(object sender, EventArgs e) {
string n = tbgoc.Text.ToString();
string t = cbPORT.Text.ToString();
serial(t, n+","); //Include a comma as data separator
}

关于c# - 从 C# 更改 for 循环中的 arduino 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35740038/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com