简体   繁体   中英

Arduino not accepting input from script

I am using an Arduino with a Raspberry Pi running a simple PHP/Python script. The Arduino code is very simple. If I send it the letter 'b', the blue light will come on:

void loop() {
  char inputMessage = Serial.read();
  if (inputMessage == 'b')
    digitalWrite(2, HIGH);
  else
    digitalWrite(2, LOW);

  // Just so there's some output
  Serial.println('.');
  delay(1000);

When I test this using the Arduino IDE's Serial Monitor feature, when I pass in 'b', the blue light comes on. Success. However, I am trying to control this from a PHP script on my Raspberry Pi, which doesn't work. The script looks like this:

$comPort = "/dev/ttyACM0";
$fp = fopen($comPort, "w+");
fwrite($fp, "b");
echo fread($fp, 10);
fclose($fp);

What's interesting here is three things.

  1. Sometimes, I get a number of . s back from when I echo (this proves that I'm making some sort of connection with the Arduino).
  2. When I run the script, the L and TX lights flash on the Arduino.
  3. The blue light does not turn on.

Does anyone see what I'm missing here? Any input is appreciated.

EDIT:

Since Python seems to be the language of choice for the Arduino/Raspberry Pi community, I've tried writing this Python script that should do the same thing as the PHP one. The results are identical, the light does not turn on. If you're a Python person and this helps you see what's wrong here, please lend a helping hand :D

import serial
ser = serial.Serial('/dev/ttyACM0',9600)
ser.write(str('b'))
print ser.readline()

What fixed it for me was I wasn't running minicom. Now I have running in a screen.

minicom -b 9600 -o -D /dev/ttyACM0

I think what the actual problem is that the Arduino board is being reset every time you open the serial port due to the RTS and DTR signals being used for auto-resetting, assuming that you are not using the Leonardo board. This means that the board was still resetting when you send the 'b' from your scripts because there isn't enough time between the auto-reset and the sending of the 'b' and therefor it is never received. The same reset occurs even when you open the Serial Monitor in the IDE. The reason why it works is because by the time you open the serial monitor window and type the letter 'b' and press enter, the board has long been reset and is eagerly waiting for your input.

There are several ways for you to handle this without having to have a separate instance of minicom running, which could cause problems down the road, like adding a delay after you open the port in your scripts (probably not the best solution but it works). I would recommend reading this question for better ways to handle it as well.

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