RasPi  Desk

C言語LED制御サンプルプログラム


*サンプルプログラムです。RasPi5の環境の差で動かないこともありますので自己責任で
 行ってください。
 教則本を基にして爺さんが編集したもので爺さんのRasPi5で動作したプログラムです
 (SPI設定が enable で動作しました。動作しない場合、何回か設定し直してみる)

 デバッグのために 無駄な printf文が入っています

*lgpioライブラリが必要
 コンパイル、リンク:lgpio.h  lgpioライブラリ

*コンパイル例(Cソースファイル名をtest.cの例)
gcc -Wall -c  test.c -llgpio -lpthread -g -O0

*リンク例(Cソースファイル名をtest.c、実行ファイル名をtestとした例)
gcc -Wall -o  test  test.c -llgpio -lpthread -g -C0


#include <stdio.h>
#include <stdlib.h>
#include <lgpio.h>
//SPIインターフェース
#define SPI_BUS         0
#define SPI_SS0         0
#define SPI_SPEED       500000 //500khz
#define SPI_MODE        0
//A/Dコンバータ MCP3008
#define MCP3008_CH0     0      // CH0入力

#define PI5             4      //Raspberry Pi 5 GPIO Chip no.
#define LED0            18     //GPIO18 for connecting LED


unsigned short Mcp3008RW(int hndAdc, unsigned char adcCh);

int main(void){
       int hndAdc;
       unsigned short adcCode = 0;
       int cnt;

       int hnd;
       int lflgOut=0;
       int iduty;

       hnd=lgGpiochipOpen(PI5);        //RasPi 5
       lgGpioClaimOutput(hnd,lflgOut,LED0,LG_LOW);

       hndAdc=lgSpiOpen(SPI_BUS,SPI_SS0,SPI_SPEED,SPI_MODE);
       cnt=100;
       while(cnt > 0){
               adcCode=Mcp3008RW(hndAdc,MCP3008_CH0);
               printf("CH0 = %3XH",adcCode);
               printf("\t電圧 = %5.3f V\n", ((3.3/1023) * adcCode));  
                         //10bit resolution:MCP3008

               iduty=(adcCode*100)/1023;

printf("duty:%d (cnt:%d)\n", iduty, cnt);

               lgTxPwm(hnd,LED0,100.0,iduty,0,0);

               lguSleep(0.5);

               cnt--;
       }

       lgGpioWrite(hnd,LED0,LG_LOW);
       lgGpiochipClose(hnd);

       lgSpiClose(hndAdc);
       return EXIT_SUCCESS;
}

unsigned short Mcp3008RW(int hndAdc, unsigned char adcCh) {
       unsigned short adcCode = 0;
       char rxBuf[3];

       char txBuf[3] = {1,0,0};      // start bit
       txBuf[1] = (8 + adcCh) << 4;  // CHAN_CONFIG_SINGLE + ADC ch

printf("txBuf:%x %x %x\n", txBuf[0],txBuf[1],txBuf[2]);

       lgSpiXfer(hndAdc,txBuf,rxBuf,sizeof(rxBuf));

printf("rxBuf:%x %x %x\n", rxBuf[0],rxBuf[1],rxBuf[2]);

       adcCode=(((rxBuf[1] & 0x03) << 8 ) | rxBuf[2]);

       return adcCode;
}