简体   繁体   中英

Using an RF module to control a motor with Arduino

I am working on a project in which 2 Arduinos are used to use wireless comunnication with the help of RF modules. The goal of the communication is to drive a motor wirelessly.

So far, I have written code for the transmitter and receiver based on example code found on this page: https://randomnerdtutorials.com/rf-433mhz-transmitter-receiver-module-with-arduino/

Following code is used to drive the transmitter module. This code is similar to the example code with modified output.

#include <RH_ASK.h>
#include <SPI.h> // Not actually used but needed to compile

RH_ASK driver;

void setup()
{
    Serial.begin(9600);    // Debugging only
    if (!driver.init())
         Serial.println("init failed");
}

void loop()
{
    const char *msg = "U";
    driver.send((uint8_t *)msg, strlen(msg));
    driver.waitPacketSent();
    delay(1000);
}

This code is used to receive the message and drive the motor

#include <RH_ASK.h>
#include <SPI.h>

const int motorPin1 = 2;
const int motorPin2 = 3;
RH_ASK driver(2000, 7, 6, 5);

const char *Up = "U";
const char *Down = "D";

void setup() {
  pinMode(motorPin1, OUTPUT);
  pinMode(motorPin2, OUTPUT);
  Serial.begin(9600);
  if (!driver.init())
    Serial.println("init failed");
}

void loop() {
    uint8_t buf[1];
    uint8_t buflen = sizeof(buf);
    if (driver.recv(buf, &buflen)) // Non-blocking
    {
      int i;
      // Message with a good checksum received, dump it.
      if ((char*)buf == Up){
        digitalWrite(motorPin1, HIGH);
        digitalWrite(motorPin2, LOW);
      }
      else if ((char*)buf == Down){
        digitalWrite(motorPin1, LOW);
        digitalWrite(motorPin2, HIGH);
      }
        else{
        digitalWrite(motorPin1, LOW);
        digitalWrite(motorPin2, LOW);
      }
      Serial.println((char*)buf);
    }
}

The final line in the receiver code is used to check via the serial interface if any message is received. This is the case. But for some reason, the message received is not the same as the provided control text. In essence, the send "U" is not the same as the character "U".

I suppose there is something wrong with the datatype of those variables. Anyone have any ideas what the problem could be?

This code is comparing pointers:

 if ((char*)buf == Up){

else if ((char*)buf == Down){

You could change it to compare the characters that are pointed to, for example:

if (buf[0] == Up[0]){

or

if( buf[0] == 'U' )

or

if( memcmp( buf, Up, 1 ) == 0 )

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