PHP / Python奇怪的行为

时间:2017-09-28 00:47:31

标签: php python html raspberry-pi

我无法理解为什么它适用于不同的文件而且它不适用于共享文件。任何可以解开这个谜团的英雄都将是我的冠军。

所以这就是我想要做的事情,PHP脚本将数据写入文件。 0,1或-1。从python脚本中读取相同的文本文件,并使伺服电机基于-1或1和0向左或向右移动。如果我自己创建一个虚拟文本文件并使python读取它,它就像一个魅力,但是当我让python脚本读取PHP修改后的文本文件时,它确实在控制台中打印了值,但是伺服器并没有。 t move !!!我不知道是否存在读/写混乱或0和1的写入方式。这是代码。

PHP脚本:

<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");

if ($_POST['leftb'])           
{ echo "Left is pressed";      // If Left button is pressed
    $txt = -1;}                // Set txt to -1


else if ($_POST['rightb'])
{ echo "Right is pressed";     // If Right button is pressed
    $txt = 1;}                 // Set txt to 1


fwrite($myfile, $txt);        // Write the value to file
fclose($myfile);              // Close file



sleep(1);                     // Wait 1 second

$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = 0;                     // Reset previous value to 0
fwrite($myfile, $txt);        // Write to the same file
fclose($myfile);              // Close the file

?>

Python脚本:

# System initialization on Raspberry Pi 3
import time
import RPi.GPIO as GPIO
initial = 5
GPIO.setmode(GPIO.BOARD)
GPIO.setup(38,GPIO.OUT)
pwm=GPIO.PWM(38,50)

# Set the servo position in the middle (5)
pwm.start(5)
position = initial

while True:

    f = open("newfile.txt","r")    # Read file written by PHP for value
    x = f.read();
    x = int(x)                     # Make sure its an integer value

    position = position + x        # Increment or decrement initial position 


    if position != initial:        # If position is different from initial position, update the servo position
        pwm.ChangeDutyCycle(position)
        print position         # Print to screen the current servo position

    else: 
        pwm.stop()             # If no new position detected, stop the servo


        f.close()              # Close the text file 
    time.sleep(0.8)

如您所见,两个程序之间共享一个公共文本文件。该文件的名称是&#34; newfile.txt&#34;。当我打开它时,我可以手动查看php脚本正在写入的数据,或者只是在终端上看到python的输出,只是它实际上并没有旋转伺服。如果我制作一个新的文本文件并手动写入-1或1或0并且伺服将完美移动,同样的事情将起作用。

我无法理解为什么两个文本文件中相同的-1或1相同?是一个字符和其他整数?我真的可以帮忙!

1 个答案:

答案 0 :(得分:0)

您是否检查过两个文件具有相同的编码,例如(ASCII与Uni​​code)?

相关问题