简体   繁体   English

基于字符控制伺服电机

[英]Controlling Servo Motor based on Characters

I've been making a simple Arduino program which involves Slave-Master I2C communication between 2 Arduino UNOs. 我一直在制作一个简单的Arduino程序,其中涉及2个Arduino UNO之间的Slave-Master I2C通信。 The Master Arduino has a Servo Motor attached to it, and the slave returns a request for 6 bytes by returning a message with six bytes. 主机Arduino上装有一个伺服电机,从机通过返回一个6字节的消息返回6字节的请求。 I want the servo motor to turn whenever a message with 6 bytes is sent, but I want it to stop turning if a message longer or shorter than 6 bytes is sent. 我希望伺服电机每发送6字节的消息就转动一次,但是我希望它在发送长于或短于6字节的消息时停止转动。 So far, I've written this code for the master: 到目前为止,我已经为母版编写了以下代码:

// Demonstrates use of the Wire library
// Reads data from an I2C/TWI slave device

#include <Wire.h>
#include <Servo.h>

Servo servo1;

void setup() {
Wire.begin();        // join i2c bus (address optional for master)
Serial.begin(9600);  // start serial for output
servo1.attach(9);
}

void loop() {
Wire.requestFrom(8, 50);    // request 6 bytes from slave device #8

while (Wire.available()) { // slave may send less than requested
char c = Wire.read(); // receive a byte as character
Serial.print(c);         // print the character
if (char c = 150)
{
  servo1.write(180);
}
else {
  servo1.write(90);
}
}

delay(500);
}

Now, when the slave sends the message "hello", regardless of character length, the motor runs at full speed. 现在,当从站发送“ hello”消息时,无论字符长度如何,电动机都将以全速运行。 What did I do wrong? 我做错了什么? Thanks. 谢谢。

if (char c = 150)

is not correct. 是不正确的。 Please make sure you understand the difference between assignment and relational operators. 请确保您了解赋值运算符和关系运算符之间的区别。

https://en.wikipedia.org/wiki/Relational_operator#Languages https://zh.wikipedia.org/wiki/Relational_operator#Languages

if you want to check if c is equal to 150 you have to write if(c == 150) 如果要检查c是否等于150,则必须编写if(c == 150)

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

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