简体   繁体   中英

Controlling Servo Motor based on Characters

I've been making a simple Arduino program which involves Slave-Master I2C communication between 2 Arduino UNOs. 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. 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. 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. 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

if you want to check if c is equal to 150 you have to write if(c == 150)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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