ex ELLA / SWSPI

Fork of SWSPI by Dave Van Wagner

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers SWSPI.cpp Source File

SWSPI.cpp

00001 /* SWSPI, Software SPI library
00002  * Copyright (c) 2012-2014, David R. Van Wagner, http://techwithdave.blogspot.com
00003  *
00004  * Permission is hereby granted, free of charge, to any person obtaining a copy
00005  * of this software and associated documentation files (the "Software"), to deal
00006  * in the Software without restriction, including without limitation the rights
00007  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
00008  * copies of the Software, and to permit persons to whom the Software is
00009  * furnished to do so, subject to the following conditions:
00010  *
00011  * The above copyright notice and this permission notice shall be included in
00012  * all copies or substantial portions of the Software.
00013  *
00014  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
00015  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
00016  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
00017  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
00018  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
00019  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
00020  * THE SOFTWARE.
00021  */
00022 
00023 #include <mbed.h>
00024 #include "SWSPI.h"
00025 
00026 SWSPI::SWSPI(PinName mosi_pin, PinName miso_pin, PinName sclk_pin)
00027     : mosi(mosi_pin),
00028       miso(NULL),
00029       sclk(sclk_pin)
00030 {
00031     if (miso_pin!= NC)
00032         miso = new DigitalIn(miso_pin);
00033     format(8);
00034     frequency();
00035 }
00036 
00037 SWSPI::~SWSPI()
00038 {
00039     delete miso;
00040 }
00041 
00042 void SWSPI::format(int bits, int mode)
00043 {
00044     this->bits = bits;
00045     polarity = (mode >> 1) & 1;
00046     phase = mode & 1;
00047     sclk.write(polarity);
00048 }
00049 
00050 void SWSPI::frequency(int hz)
00051 {
00052     // TODO: need wait_ns taking int
00053     this->delay_us = 500000/hz;
00054 }
00055 
00056 int SWSPI::write(int value)
00057 {
00058     int read = 0;
00059     for (unsigned bit = 1 << (bits-1); bit; bit >>= 1)
00060     {
00061         mosi.write((value & bit) != 0);
00062 
00063         if (phase == 0)
00064         {
00065             if (miso && miso->read())
00066                 read |= bit;
00067         }
00068 
00069         sclk.write(!polarity);
00070 
00071         if (delay_us) wait_us(delay_us);
00072 
00073         if (phase == 1)
00074         {
00075             if (miso && miso->read())
00076                 read |= bit;
00077         }
00078 
00079         sclk.write(polarity);
00080 
00081         if (delay_us) wait_us(delay_us);
00082     }
00083     
00084     return read;
00085 }