Homer
Published © LGPL

PHPoC - Scratch Programming 102

Let's continue to "scratch" with PHPoC. Check out some basic tutorials in this Scratch programming with PHPoC.

BeginnerFull instructions provided1 hour864

Things used in this project

Hardware components

PHPoC Blue
PHPoC Blue
×1
Servos (Tower Pro MG996R)
×1
Rotary angle sensor
×1
PHPoC PWM & Sensor Expansion Board
PHPoC PWM & Sensor Expansion Board
Optional
×1

Software apps and online services

Scratch Editor 2.0 Offline
Node.js

Story

Read more

Code

task0.php

PHP
This script is used to process data and execute commands on PHPoC board.
<?php

if(_SERVER("REQUEST_METHOD"))
	exit; // avoid php execution via http request

include_once "/lib/sd_340.php";
include_once "/lib/sn_tcp_ws.php";

define("WS_ID", 0);
define("WS_PATH", "scratch_test");

// Define output servo motor
define("PWM_PERIOD", 20000); // 20000us (20ms)
define("WIDTH_MIN", 600);
define("WIDTH_MAX", 2450);


$uio_list = array(8, 9, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21);
for($i=0; $i<12;$i++){
    uio_setup(0, $uio_list[$i], "in_pu"); 
}

uio_setup(0, 30, "out high");
uio_setup(0, 31, "out high");

function servo_set_angle($pin, $angle){
	$angle= 90 - $angle;
	if($angle < 0)
		$angle = 0;
	if($angle > 180)
		$angle = 180;
	$width = WIDTH_MIN + (int)round((WIDTH_MAX - WIDTH_MIN) * $angle / 180.0);
	if(($width >= WIDTH_MIN) && ($width <= WIDTH_MAX))
		ht_pwm_width(0, $width, PWM_PERIOD);
}

ws_setup(WS_ID, WS_PATH, "csv.phpoc");
$rwbuf = "";

while(1)
{
	if(ws_state(WS_ID) == TCP_CONNECTED)
	{
		$rlen = ws_read_line(WS_ID, $rwbuf);

		if($rlen)
		{
			$cmd = explode("/",$rwbuf);
			switch($cmd[1]){
			case "dW":
				$pin = (int)$cmd[2];
                uio_setup(0, $pin, "out high");
				if ($cmd[3] == "LOW")
					uio_out(0, $pin, LOW);			
				else
					uio_out(0, $pin, HIGH);
				break;
			case "lW":
				$pin = (int)$cmd[2]+29;
				echo $pin,"\r\n";
				if ($cmd[3] == "on")
					uio_out(0, $pin, LOW);			
				else
					uio_out(0, $pin, HIGH);
				break;
			case "svW":
				ht_pwm_setup((int)$cmd[2], (WIDTH_MIN + WIDTH_MAX) / 2, PWM_PERIOD, "us");
			    servo_set_angle((int)$cmd[2], (int)$cmd[3]);
				break;
			case "dR":
				uio_setup(0, (int)$cmd[2], "in_pu"); 
				break;
			case "poll":
				$ret = "";					
                for($i=0; $i<12;$i++){
					$pin = $uio_list[$i];
					$d_in = uio_in(0, $pin);
					$ret = $ret."dR/".(string)$pin." ".(string)$d_in."\n";
				}
				for($pin=0; $pin<=5;$pin++){
					adc_setup(0, $pin);
					$adc_in = adc_in(0, 30);
					$ret = $ret."aR/".(string)$pin." ".(string)$adc_in."\n";
				}
				ws_write(0, $ret);			
				usleep(200000);
				break;
			case "reset_all":
                for($i=0; $i<12;$i++){
					uio_setup(0, $uio_list[$i], "in_pu"); 
				};			
                uio_out(0, 30, HIGH);
                uio_out(0, 31, HIGH);    
				break;				
			
			}			
		}
	}
	
}
 
?>

Credits

Homer

Homer

17 projects • 46 followers

Comments