Search code examples
linuxarduinoarduino-unoserial-communicationusbserial

I cannot send data to my Arduino through usb serial connection


So, I have an arduino uno R3 SMD edition and I want to send commands to it while it's running. It has an adafruit v2 motor shield connected to it, which is powered separately from the arduino. The arduino is connected to my laptop by a usb cable.

Now, the motor shield works and I can send code to the arduino to make it do things. I can't get the arduino to receive anything I send to it while it's running from the serial connection though. I can print to the monitor in the arduino ide from arduino code though. I'm on debian linux stretch btw. My arduino ide is from the debian repos.

Here is all the code I'm trying to use:

Arduino Code

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"

Adafruit_MotorShield AFMS = Adafruit_MotorShield();

Adafruit_StepperMotor *myMotor = AFMS.getStepper(200, 2);

void setup()
{
        Serial.begin(115200);
        AFMS.begin();
        myMotor->setSpeed(300);
}

char input;
int dir;

void loop()
{
        dir = 0;
        if (Serial.available() > 0) {
                input = Serial.read();
                Serial.print(input);

                if (input == 1) {
                        dir = FORWARD;
                }
                if (input == 2) {
                        dir = BACKWARD;
                }
        }

        if (dir != 0) {
                myMotor->step(360, dir, DOUBLE);
                delay(1000);
        }
}

Controller Code on Laptop

#include <stdlib.h>
#include <stdio.h>

int
main(int argc, char **argv)
{
        FILE *arduino;
        int c;

        arduino = fopen("/dev/ttyACM0", "w");

        if (arduino == NULL) {
                fprintf(stdout, "NOOOOOOOOOOOO\n");
        }

        while (1) {
                c = fgetc(stdin);

                if (c == 'f') {
                        fprintf(arduino, "%d", 1); 
                }
                if (c == 'b') {
                        fprintf(arduino, "%d", 2); 
                }

                fflush(arduino);

                if (c == 'q') {
                        break;
                }
        }

        return 0;
}

I'm pretty sure this isn't a permissions problem, I've run the controller code from root and the tty device opens fine. Also, I've tried both 9600 and 115200 for my baud rate, but no dice. Does anyone have an idea? From googling it really seems like this is all anyone else is doing.


Solution

  • Your controller is sending characters '1' and '2'. Your Arduino is checking for character codes 1 and 2 - in other words, the characters CtrlA and CtrlB. You can make the change at either end, they just need to match.