Arduino开发板ICSP接口中MOSI, MISO,SCK为SPI接口,有的开发板D11,D12,D13管脚默认和SPI接口连接(如UNO PLUS),有的开发板默认不连接。Accessory Shield开发板中OLED则是通过SPI接口控制。但本章教程作为Arduino的入门教程,OLED的程序较为复杂,在这里不打算讲解OLED的程序。在这里一Arduino IDE自带的例程讲解如何使用Arduino的SPI接口。 点击File->Examples->SPI->DigitalPotControl打开工程。程序如下: // inslude the SPI library: #include <SPI.h> // set pin 10 as the slave select for the digital pot: const int slaveSelectPin = 10; void setup() { // set the slaveSelectPin as an output: pinMode (slaveSelectPin, OUTPUT); // initialize SPI: SPI.begin(); } void loop() { // go through the six channels of the digital pot: for (int channel = 0; channel < 6; channel++) { // change the resistance on this channel from min to max: for (int level = 0; level < 255; level++) { digitalPotWrite(channel, level); delay(10); } // wait a second at the top: delay(100); // change the resistance on this channel from max to min: for (int level = 0; level < 255; level++) { digitalPotWrite(channel, 255 - level); delay(10); } } } void digitalPotWrite(int address, int value) { // take the SS pin low to select the chip: digitalWrite(slaveSelectPin, LOW); // send in the address and value via SPI: SPI.transfer(address); SPI.transfer(value); // take the SS pin high to de-select the chip: digitalWrite(slaveSelectPin, HIGH); } 程序分析: 程序开始先引入SPI头文件SPI.h。SPI接口包含MOSI, MISO,SCK,CS四根线。其中MOSI, MISO,SCK已经固定引脚。而CS为片选引脚,可随意选择哪个引脚作为CS.程序中const int slaveSelectPin = 10;定义D10作为片选信号。 setup()函数中调用SPI.begin()初始化SPI接口。此处为默认设置。若要设置具体参数可使用如下语句初始化SPI. SPI.beginTransaction(SPISettings(14000000, MSBFIRST, SPI_MODE0)); SPISettings()函数设置SPI传输模式,SPI.beginTransaction()函数根据SPISettings()初始化SPI. 此处为设置SPI速率为14MHZ,高位先传输,模式0。 digitalWrite(slaveSelectPin, LOW); 传输SPI前先拉低片选管脚,使能SPI设备。 SPI.transfer(val); SPI传输函数,参数val为要发送的字节,函数返回值为接收到的数据。 digitalWrite(slaveSelectPin, HIGH); SPI传输结束释放片选管脚。 |