gpt4 book ai didi

c - Arduino串口阅读

转载 作者:太空狗 更新时间:2023-10-29 15:39:42 25 4
gpt4 key购买 nike

我正在使用网络控制的漫游器并使用串行端口与 Arduino 进行通信.我编写了一些仅使用 fwrite() 并将 ASCII 1 或 ASCII 2 写入串行端口的 PHP。 Arduino 正在监听那个端口并根据它听到的内容做一些事情。我知道我的 PHP 正在工作,因为每当我告诉它发送东西时,Arduino 都会收到它。这是 Arduino 代码:

//This listens to the serial port (USB) and does stuff based on what it is hearing.

int motor1Pin = 13; //the first motor's port number
int motor2Pin = 12; //the second motor's port number
int usbnumber = 0; //this variable holds what we are currently reading from serial


void setup() { //call this once at the beginning
pinMode(motor1Pin, OUTPUT);
//Tell arduino that the motor pins are going to be outputs
pinMode(motor2Pin, OUTPUT);
Serial.begin(9600); //start up serial port
}

void loop() { //main loop
if (Serial.available() > 0) { //if there is anything on the serial port, read it
usbnumber = Serial.read(); //store it in the usbnumber variable
}

if (usbnumber > 0) { //if we read something
if (usbnumber = 49){
delay(1000);
digitalWrite(motor1Pin, LOW);
digitalWrite(motor2Pin, LOW); //if we read an ASCII 1, stop
}

if (usbnumber = 50){
delay(1000);
digitalWrite(motor1Pin, HIGH);
digitalWrite(motor2Pin, HIGH); //if we read an ASCII 2, drive forward
}

usbnumber = 0; //reset
}
}

所以这应该是相当简单的。现在,当我发送 ASCII 1 或 ASCII 2 时,我正在测试的 LED(在引脚 13 上)打开并保持打开状态。但是,如果我发送另一个 ASCII 1 或 2,它会关闭然后重新打开。目标是仅当 ASCII 1 是最后发送的内容时才打开它,并保持打开状态直到 2 是最后发送的内容。

编辑:这是我的 PHP:

<?php
$verz="0.0.2";
$comPort = "com3"; /*change to correct com port */

if (isset($_POST["rcmd"])) {
$rcmd = $_POST["rcmd"];
switch ($rcmd) {
case Stop:
$fp =fopen($comPort, "w");
fwrite($fp, chr(1)); /* this is the number that it will write */
fclose($fp);


break;
case Go:
$fp =fopen($comPort, "w");
fwrite($fp, chr(2)); /* this is the number that it will write */
fclose($fp);
break;
default:
die('???');
}
}
?>
<html>
<head><title>Rover Control</title></head>
<body>
<center><h1>Rover Control</h1><b>Version <?php echo $verz; ?></b></center>

<form method="post" action="<?php echo $PHP_SELF;?>">
<table border="0">
<tr>
<td></td>
<td>

</td>
<td></td>
</tr>
<tr>
<td>
<input type="submit" value="Stop" name="rcmd"><br/>
</td>
<td></td>
<td>
<input type="submit" value="Go" name="rcmd"><br />
</td>
</tr>
<tr>
<td></td>
<td><br><br><br><br><br>

</td>
<td></td>
</tr>
</table>
</form>
</body>
</html>

最佳答案

如果它是 C 那么你在两个测试中都有 assignment 而不是 comparison,所以两者都是 true,所以每次都完成所有写入.使用高警告级别编译(如 GCC 中的 -Wall -pedantic)。试试这个:


int a = 0;
if ( a == 1 ) printf( "a is not one: %d\n", a );
if ( a = 1 ) printf( "a is one: %d\n", a );

从您发布的 PHP 代码(我不是这里的专家)看来您正在将二进制 1 写为 char,它不是 ASCII 49,而是 ASCII 1 (soh),与 2 相同。尝试将其更改为'1' 在 PHP 代码中(或 1 在 C 代码中。)

这是关于 Controlling the Serial Port with PHP 的一些文章的链接- 我用谷歌搜索,不知道它的质量 - 但看起来仅仅将一个整数写入“com1”是不够的 - 这超出了我的领域,祝你好运:)

关于c - Arduino串口阅读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/899098/

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