Last active
August 29, 2015 14:20
-
-
Save cfelton/2a0106edc5bd2b1bec4c to your computer and use it in GitHub Desktop.
simple ADXL345 model (3-wire SPI only)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from __future__ import division | |
from __future__ import print_function | |
from random import randint | |
from myhdl import * | |
class ADXL345(object): | |
''' This is a model of the ADXL345 ... | |
''' | |
def __init__(self, name='ADXL345'): | |
self.name = name | |
def _tristate_driver(self, driver, pinsig, biti, bito): | |
@always_comb | |
def mdl_sdat_in(): | |
if not pinsig: | |
biti.next = False | |
else: | |
biti.next = True | |
# bidirection (emulated open-collector) only need to pull | |
# the signal low, external pull-ups drive the signal high. | |
@always_comb | |
def mdl_sdat_out(): | |
if not bito: | |
driver.next = False | |
else: | |
driver.next = None | |
return mdl_sdat_in, mdl_sdat_out | |
def process(self, I2C_SCLK, I2C_SDAT, G_SENSOR_CS_N, G_SENSOR_INT): | |
''' | |
:param I2C_SCLK: | |
:param I2S_SDAT: | |
:param G_SENSOR_CS_N: | |
:param G_SENSOR_INT: | |
:return: | |
The following is only a functional model, it is not intended | |
to be convertible / synthesizable! | |
''' | |
# alias some of the signals | |
scl = I2C_SCLK | |
csn = G_SENSOR_CS_N | |
# SDAT is a bi-direction signal, emulate a tristate driver | |
#print(type(I2C_SCLK)) | |
#assert isinstance(I2C_SDAT, TristateSignal) | |
sdatd = I2C_SDAT.driver() | |
sdato = Signal(bool(1)) # sdat output | |
sdati = Signal(bool(0)) # sdat input | |
# simple model of a tristate driver | |
gtri = self._tristate_driver(sdatd, I2C_SDAT, sdati, sdato) | |
@instance | |
def mdl_adxl(): | |
while True: | |
# should only be here if CSN and SCL are high | |
assert csn and scl | |
yield csn.negedge | |
if csn == False: | |
# SPI mode | |
assert scl | |
elif sdati == False: | |
raise NotImplementedError | |
# @todo SPI or I2C mode | |
yield scl.negedge | |
yield scl.posedge | |
rw = bool(sdati) | |
yield scl.posedge | |
mb = bool(sdati) | |
addr = 0 | |
for ii in range(6): | |
yield scl.posedge | |
addr = addr + (int(sdati) << ii) | |
# have captured the first 8 bits, no read or write | |
# the next 8 bits | |
valo = intbv(randint(0, 255))[8:] | |
vali = intbv(0)[8:] | |
print("rw:{:d}: addr:{:02X}".format(int(rw), addr)) | |
for ii in range(7, -1, -1): | |
if rw: | |
sdato.next = valo[ii] | |
else: | |
vali[ii] = int(sdati) | |
yield scl.posedge | |
print("i:{:02X}, o:{:02X}".format(int(vali), int(valo))) | |
sdato.next = True | |
yield csn.posedge | |
return instances() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment