*/ namespace NoccyLabs\Gpio\Bus; class SoftwareSpiBus extends Bus { protected $buffer = null; protected function configure() { $this->addPin("sclk"); $this->addPin("mosi"); $this->addPin("miso"); } protected function spiExchangeByte($byte) { $in = 0; if (is_string($byte)) { $byte = ord($byte); } for($bit=0; $bit<8; $bit++) { $this->setValue("sclk", 0); $this->setValue("mosi", (($byte & 1<<$bit)>0)); usleep(5000); $this->setValue("sclk", 1); usleep(5000); if ($this->getValue("miso")) { $in |= 1<<$bit; } } return chr($in); } protected function setValue($pin,$value) { echo "{$pin}→{$value}\n"; } protected function getValue($pin) { echo "{$pin}←0\n"; return 0; } public function write($data) { for($n = 0; $n < strlen($data); $n++) { $this->buffer .= $this->spiExchangeByte($data[$n]); } } public function read($bytes) { $ret = null; if (strlen($this->buffer)>0) { if (strlen($this->buffer)<$bytes) { $ret = $this->buffer; $bytes -= strlen($this->buffer); $this->buffer = null; } else { $ret = substr($this->buffer,0,$bytes); $this->buffer = substr($this->buffer,$bytes); return $ret; } } for($n = 0; $n < $bytes; $n++) { $ret.= $this->spiExchangeByte(0x00); } return $ret; } public function getBufferFill() { return strlen($this->buffer); } }