V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
morning
V2EX  ›  Python

如何理解 Python_Spidev 的 spi.xfer2 方法? (时序图 位操作)

  •  
  •   morning · 2015-09-07 17:50:41 +08:00 · 6897 次点击
    这是一个创建于 3163 天前的主题,其中的信息可能已经有所发展或是发生改变。

    间单点说就是对时序图及相关操作理解不到位,python 这边也就卡住了~

    连接方式:温度传感器 -> ADC -> 树莓派,

    在树莓派上使用 SPI,用到 Python Spidev

    ADC 我用的是 ADC0832 (2 通道,8 位),搜到的教程都是以 MCP3008 (8 通道,10 位)为例子,对照着弄了一下,接线大概没什么问题了,

    但是代码部分 analog_read (channel )这个函数没看懂.

    我用 CH0 作为输入端,也就是需要设置 (Din = 1, Dout = 0 ),从哪里设置?

    adc_tmp36.py

    import spidev, time
    
    spi = spidev.SpiDev ()
    spi.open (0,0 )
    
    def analog_read (channel ):
        # !下面这两行不懂!
        r = spi.xfer2 ([1, (8 + channel ) << 4, 0]) 
        adc_out = ((r[1]&3 ) << 8 ) + r[2]  #3 字节?
        return adc_out
    
    while True:
        reading = analog_read (0 )
        voltage = reading * 3.3 / 1024
        temp_c = voltage * 100 - 50
        temp_f = temp_c * 9.0 / 5.0 + 32
        print ("Temp C=%f\t\tTemp f=%f" % (temp_c, temp_f ))
        time.sleep (1 )
    

    https://github.com/simonmonk/raspberrypi_cookbook/blob/master/code/adc_tmp36.py

    用到的方法:

    open (bus, device )
    
    xfer2 (list of values[, speed_hz, delay_usec, bits_per_word])
    #Performs an SPI transaction. Chip-select should be held active 
    #between blocks.
    

    https://github.com/doceme/py-spidev

    ADC0832 datasheet:

    http://html.alldatasheet.com/html-pdf/158145/NSC/ADC0832CCN/120/2/ADC0832CCN.html
    http://blog.sina.com.cn/s/blog_66eab1060100j78l.html

    MCP3008 datasheet 和 连接方法(跟我看的那个例子比较像):

    http://atceiling.blogspot.com/2014/04/raspberry-pi-mcp3008.html#.Ve01WXvG6JU

    http://tec.gekius.com/blog/935.html

    1 条回复    2015-09-09 18:21:27 +08:00
    morning
        1
    morning  
    OP
       2015-09-09 18:21:27 +08:00
    懂了,xfer 方法本事只负责按一定格式输入,并返回相同格式.也就是说往里边写什么,读取的数据要怎么处理都由你自己来做.
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   887 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 22:57 · PVG 06:57 · LAX 15:57 · JFK 18:57
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.