ChubbyChocolate
ChubbyChocolate

Reputation: 246

Raspberry php not sending serial data to arduino

I have a raspberry with 2 php pages in /var/www, one is led1off.php the other is led1on.php. I also have 2 Python scripts in cgi-bin led1off.py & led1on.py

led1off.py

#!/usr/bin/env python 
Import serial
ser0 = serial.Serial('/dev/ttyACM0'), 9600)
ser0.write('2')

led1on.py

#!/usr/bin/env python 
Import serial
ser0 = serial.Serial('/dev/ttyACM0'), 9600)
ser0.write('1')

--

led1on.php

<?php
exec('sudo -u www-data python /usr/lib/cgi-bin/led1on.py')
?>

led1off.php

<?php
exec('sudo -u www-data python /usr/lib/cgi-bin/led1off.py')
?>

What should happen in theory is when I load http://192.168.0.2/led1on.php The php script should run its code in the terminal so that it executes led1on.py. Then led1on.py should send "1" to the arduino which turns on an led. Similar thing goes for led1off.php.

The thing is I am able to type

sudo -u www-data python /usr/lib/cgi-bin/led1on.py

In the terminal, and when I do it, the led on the arduino turns on. So the code on the arduino is correct, there is comunication between the 2, and the Python code is correct. The problem is that it doesn't work when I load the php from a browser. Am I doing something wrong? Do I need to give special permissions to www-data to send serial data?

Upvotes: 1

Views: 466

Answers (1)

Kamil Wozniak
Kamil Wozniak

Reputation: 445

To run command as Super user www-data should be in /etc/sudoers - could you check if it is there?

Similar question was asked here: sudo in php exec()

As we found during discussion, this code will run correctly:

<?php
$command = escapeshellcmd('sudo /usr/lib/cgi-bin/led1on.py');
$output = shell_exec($command);
echo $output;
?>

Hope this helps.

Upvotes: 1

Related Questions