Lazarus로 Raspberry PI의 GPIO제어 (LED 컨트롤)

Programming/Delphi 2016.03.13 22:18 Posted by 파란크리스마스

출처 : Lazarus on Raspberry Pi
RaspberyPi rpi_hal Hardware Abstraction Library

라이브러리 다운로드

rudiratlos/rpi-hal 다운로드

rpi_hal 버그가 있어서 제가 수정했습니다. 압축된 소스 파일에 수정된 rpi_hal.pas 파일을 첨부했습니다.

빌드옵션

빌드 옵션으로 UseCThreads 추가가 필요합니다.

소스

RaspberryPI LED.7z

unit Unit1;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
  rpi_hal;

type

  { TForm1 }

  TForm1 = class(TForm)
    ToggleBox1: TToggleBox;
    ToggleBox2: TToggleBox;
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure ToggleBox1Change(Sender: TObject);
    procedure ToggleBox2Change(Sender: TObject);
  private
    { private declarations }
    isr_1 : isr_t;
    isr_2 : isr_t;
  public
    { public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.lfm}

{ TForm1 }

const
  GPIO20 = 20;
  GPIO21 = 21;

function my_isr(gpio_nr:integer):integer;
// for gpio_int testing. will be called on interrupt
const waittim_ms=1;
begin
  writeln ('my_isr fired for GPIO',gpio_nr,' servicetime: ',waittim_ms:0,'ms');
  sleep(waittim_ms);
  my_isr:=999;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  writeln('Show CPU-Info, RPI-HW-Info and Registers:');
  rpi_show_all_info;

  isr_1.gpio := GPIO20;
  isr_1.rising_edge := true;
  gpio_set_int(isr_1, GPIO20, @my_isr, true, OUTPUT);
  gpio_int_enable(isr_1);

  isr_2.gpio := GPIO21;
  isr_2.rising_edge := true;
  gpio_set_int(isr_2, GPIO21, @my_isr, true, OUTPUT);
  gpio_int_enable(isr_2);
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  gpio_int_disable(isr_1);
  gpio_int_release(isr_1);

  gpio_int_disable(isr_2);
  gpio_int_release(isr_2);
end;

procedure TForm1.ToggleBox1Change(Sender: TObject);
begin
  gpio_set_pin(isr_1.gpio, ToggleBox1.Checked);
end;

procedure TForm1.ToggleBox2Change(Sender: TObject);
begin
  gpio_set_pin(isr_2.gpio, ToggleBox2.Checked);
end;

end.

실행

$ chmod 755 raspi_led
$ sudo ./raspi_led


저작자 표시
신고

MacOS에 CodeTyphon 설치

Programming/Delphi 2016.01.07 14:12 Posted by 파란크리스마스

출처 : CT on MacOS X 10.11.x (El Capitan)
PilotLogic - MacOS - Detail Installation
PilotLogic - Setup Script Options

0. CodeTyphon 삭제 ( 기본에 설치되어 있는 경우)

$ cd /usr/local
$ sudo rm -Rf codetyphon

1. xcode 설치

2. xcode command tool 설치

$ xcode-select --install

3. XQuartz 설치

XQuartz 2.7.8 (For OS X 10.6.3 or later (including El Capitan) 다운로드

XQuartz 미설치 오류

4. MacPorts 설치

MacPorts OS X 10.11 El Capitan 다운로드

5. 사용자 sudo 권한 부여

$ sudo vi /etc/sudoers

내용추가 - bluesanta 사용자의 root권한 부여

bluesanta       ALL=(ALL) NOPASSWD: ALL

6. CodeTyphon 다운로드 및 설치

다운로드

설치 스크립트(install.sh) 실행

$ cd Downloads/CodeTyphonIns
$ ./install.sh
  
====================================================
             CodeTyphon Studio 
            Version 5.60 (GEN V)
   Installation for: Linux-Solaris-FreeBSD-MacOS
====================================================
 
WARNING: Improper use of the sudo command could lead to data loss
or the deletion of important system files. Please double-check your
typing when using sudo. Type "man sudo" for more information.
 
To proceed, enter your password, or type Ctrl-C to abort.
 
Password:

CodeTyphon 설치

 
   0) Install CodeTyphon Studio
  
   9) Exit
  
>>> Select an action (press 0..9 key): 0

설치 스크립트 종료

====================================================
  CodeTyphon Studio 5.60 Setup for Darwin64
   Settings: Platform=carbon  Multiarch Mode=1
====================================================
   
   0) Install System Libraries
   1) Run CodeTyphon Center (CTC)
   
     11) -- Platform (widget) Setup
     12) -- Multi-Architecture Setup
   
   3) Remove FreePascal
   4) Remove and Build FreePascal
   
   5) Remove Typhon IDE
   6) Remove and Build Typhon IDE
   
   7) Remove ALL
   8) Remove and Build ALL
   
   9) EXIT
   
>>>  Select an action (press 0..9 key): 9

7. Install System Libraries


8. 모두(FPC, Typhon, COcean) 빌드 하기


// shryu

{$IFDEF FPC}

  type HWND = type THandle;

{$ENDIF}







저작자 표시
신고

출처 : 델마당 - 라즈베리 파이(Raspberry Pi) 보드 크로스 컴파일 환경 구축 성공(Win7 => 라즈베리)
Cross-Build for RasberryPi
TOPIC: How to build app for Raspberry Pi from Windows 7
Setup Cross Compile For ARM

Lazarus

Lazarus라는 RAD툴 입니다.
아직 설치 방법은 작성중이고, 우선 개발된 소스와 실행 파일을 올립니다.
기본언어는 Pascal 이고, 상용툴로 Delphi와 비슷합니다.
Raspberry PI용 화면개발을 하실 일이 있다면 편하게 작성하실수 있습니다.

설치방법과 GPIO관련 내용은 따로 작성해서 올리겠습니다.

GPIO 컴포넌트

rpi-hal 링크

CodeTyphon 다운로드

Cross-Build for RasberryPi 다운로드

설치

CodeTyphonIns\install.bat 관리자로 실행

Lazarus 실행

화면디자인

소스코드 Unit1.pas project1.zip

unit Unit1;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls;

type

  { TForm1 }

  TForm1 = class(TForm)
    Button1: TButton;
    Edit1: TEdit;
    procedure Button1Click(Sender: TObject);
  private
    { private declarations }
  public
    { public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.lfm}

{ TForm1 }

procedure TForm1.Button1Click(Sender: TObject);
begin
  //
  Edit1.Text := 'Hello Raspberry !!!';
end;

end.

Windows에서 실행

 

Raspberry PI 용 컴파일 옵션 설정

Raspberry PI에서 실행

 

저작자 표시
신고

Delphi - TEncoding.Unicode.GetString

Programming/Delphi 2014.10.22 01:04 Posted by 파란크리스마스

출처 : Delphi - Http POST call
TStream.ReadBuffer Method
TEncoding.GetString Method (TBytes)

procedure TForm1.Button2Click(Sender: TObject);
var
  tmpBuffer, Buffer: TBytes;
  LFileStream: TFileStream;
  test : String;
begin
  //
  LFileStream := TFileStream.Create(Path + 'test.smi', fmOpenRead);

  try
    Memo1.Lines.BeginUpdate;

    // Read file into buffer
    SetLength(Buffer, LFileStream.Size);
    LFileStream.ReadBuffer(Buffer[0], Length(Buffer));

    SetLength(tmpBuffer, Length(Buffer)-2);
    CopyMemory(tmpBuffer, @Buffer[2], Length(Buffer)-2  );

    test := TEncoding.Unicode.GetString(Buffer);
    Memo1.Lines.Add(test);
  finally
    Memo1.Lines.EndUpdate;
    LFileStream.Free;
  end;
end;


신고

Delphi - Http POST call

Programming/Delphi 2013.11.29 10:18 Posted by 파란크리스마스

Delphi - Http POST call

DelphiHttpPostCall.7z

procedure TForm1.Button1Click(Sender: TObject);
var
  sl : TStringList;
  ResponseStream: TMemoryStream;
  resultBytes: TBytes;
begin
  sl := TStringList.Create;
  ResponseStream := TStringStream.Create;
  try
    IdHTTP1.Request.ContentType := 'application/x-www-form-urlencoded';
    sl.Add('id=' + Edit2.Text);
    IdHTTP1.Post(Edit1.Text, sl, ResponseStream);
    ResponseStream.Position := 0;

    SetLength(resultBytes, ResponseStream.Size);
    ResponseStream.ReadBuffer(resultBytes[0], Length(resultBytes));

    Memo1.Lines.Text := TEncoding.UTF8.GetString(resultBytes);
  finally
    sl.Free;
    ResponseStream.Free;
  end;
end;
신고
TAG Delphi, HTTP, post

Delphi - Byte 관련 Tip

Programming/Delphi 2013.03.05 17:05 Posted by 파란크리스마스

Delphi - Byte 관련 Tip

function BytesToHex(aSource: TBytes): string;
begin
  SetLength(Result, Length(aSource) * 2);
  if Length(aSource) > 0 then
    BinToHex(aSource[0], PChar(Result), Length(aSource));
end;

procedure TForm1.Button1Click(Sender: TObject);
const
  SetupLdrExeHeaderOffset = $01d204;
  A: Array[0..3] of Byte = ($EF, $BE, $AD, $DE);
var
  HInstance: THandle;
  filename: String;
  FileStream: TFileStream;
  ArrayBytesHeader, ArrayBytesHeaderStr : TBytes;
  HeaderStr : String;
begin
  // AbZipper1.FileName := 'C:\AAPlus4PC_server\ALZip861.exe';
  filename := 'C:\AAPlus4PC_server\ALZip861.exe';

  FileStream := TFileStream.Create(filename, fmOpenRead);
  try

    FileStream.Seek( SetupLdrExeHeaderOffset , soBeginning);

    SetLength( ArrayBytesHeader, 16 );
    FileStream.ReadBuffer(ArrayBytesHeader, 16);

    if (CompareMem(ArrayBytesHeader, @A, 4)) then begin
      SetLength(ArrayBytesHeaderStr, 12);
      CopyMemory( ArrayBytesHeaderStr, @ArrayBytesHeader[4], 12  );

      HeaderStr := TEncoding.ASCII.GetString(ArrayBytesHeaderStr);
      //Memo1.Lines.Add( BytesToHex(ArrayBytesHeader) );
      //Memo1.Lines.Add( BytesToHex(ArrayBytesHeaderStr) + '/' + HeaderStr );

      if HeaderStr='NullsoftInst' then begin
        Memo1.Lines.Add( 'ooooo' );
      end else begin
        Memo1.Lines.Add( 'xxxxx - 2' );
      end;

    end else begin
      Memo1.Lines.Add( 'xxxxx - 1' );
    end;
  finally
    SetLength(ArrayBytesHeader, 0);
    SetLength(ArrayBytesHeaderStr, 0);
    FileStream.Free;
  end;
end;
신고

Delphi 버전별 Alias

Programming/Delphi 2013.02.12 14:51 Posted by 파란크리스마스

D7 for Delphi 7
D9 for Delphi 2005
D10 for Delphi 2006
D11 for Delphi 2007
D12 for Delphi 2009
D14 for Delphi 2010
D15 for Delphi XE
D16 for Delphi XE2
D17 for Delphi XE3

신고

Delphi Tip

Programming/Delphi 2012.04.13 10:41 Posted by 파란크리스마스

출처

http://rainflys.tistory.com/84
http://www.borlandforum.com/impboard/impboard.dll?action=read&db=del_qna&no=3570
http://bloodguy.tistory.com/entry/Delphi-바탕화면-시작메뉴프로그램-등-특수-디렉토리-가져오기

현재 실행 폴더 구하기

runpath:=ExtractFilePath(Application.ExeName);

Memo 스크롤 마지막으로 이동

procedure TForm1.Memo1Change(Sender: TObject);
begin
  Memo1.Perform(EM_LINESCROLL, 0, Memo1.Lines.Count);
end;

Format

 format('%0.10d',[10])

시스템 폴더 조회

// 시작 메뉴\프로그램 (C:\Documents and Settings\USER_NAME\시작 메뉴\프로그램)
SHGetFolderPath(0, CSIDL_PROGRAMS, 0, 0, PathPrograms);   
 
// 바탕 화면 (C:\Documents and Settings\USER_NAME\바탕 화면)
SHGetFolderPath(0, CSIDL_DESKTOP, 0, 0, PathDesktop);
unit Winapi.ShlObj;

  CSIDL_DESKTOP                 = $0000;          // 바탕화명 <desktop>
  CSIDL_INTERNET                = $0001;          // Internet Explorer (icon on desktop)
  CSIDL_PROGRAMS                = $0002;          //  시작메뉴\프로그램 Start Menu\Programs
  CSIDL_CONTROLS                = $0003;          // My Computer\Control Panel
  CSIDL_PRINTERS                = $0004;          // My Computer\Printers
  CSIDL_PERSONAL                = $0005;          // My Documents
  CSIDL_FAVORITES               = $0006;          // <user name>\Favorites
  CSIDL_STARTUP                 = $0007;          // Start Menu\Programs\Startup
  CSIDL_RECENT                  = $0008;          // <user name>\Recent
  CSIDL_SENDTO                  = $0009;          // <user name>\SendTo
  CSIDL_BITBUCKET               = $000a;          // <desktop>\Recycle Bin
  CSIDL_STARTMENU               = $000b;          // <user name>\Start Menu
  CSIDL_MYDOCUMENTS             = CSIDL_PERSONAL; // Personal was just a silly name for My Documents
  CSIDL_MYMUSIC                 = $000d;          // "My Music" folder
  CSIDL_MYVIDEO                 = $000e;          // "My Videos" folder
  CSIDL_DESKTOPDIRECTORY        = $0010;          // <user name>\Desktop
  CSIDL_DRIVES                  = $0011;          // My Computer
  CSIDL_NETWORK                 = $0012;          // Network Neighborhood (My Network Places)
  CSIDL_NETHOOD                 = $0013;          // <user name>\nethood
  CSIDL_FONTS                   = $0014;          // windows\fonts
  CSIDL_TEMPLATES               = $0015;

  CSIDL_COMMON_STARTMENU        = $0016;          // All Users\Start Menu
  CSIDL_COMMON_PROGRAMS         = $0017;          // All Users\Start Menu\Programs
  CSIDL_COMMON_STARTUP          = $0018;          // All Users\Startup
  CSIDL_COMMON_DESKTOPDIRECTORY = $0019;          // All Users\Desktop
  CSIDL_APPDATA                 = $001a;          // <user name>\Application Data
  CSIDL_PRINTHOOD               = $001b;          // <user name>\PrintHood
  CSIDL_LOCAL_APPDATA           = $001c;          // <user name>\Local Settings\Applicaiton Data (non roaming)
  CSIDL_ALTSTARTUP              = $001d;          // non localized startup
  CSIDL_COMMON_ALTSTARTUP       = $001e;          // non localized common startup
  CSIDL_COMMON_FAVORITES        = $001f;
  CSIDL_INTERNET_CACHE          = $0020;
  CSIDL_COOKIES                 = $0021;
  CSIDL_HISTORY                 = $0022;
  CSIDL_COMMON_APPDATA          = $0023;          // All Users\Application Data
  CSIDL_WINDOWS                 = $0024;          // GetWindowsDirectory()
  CSIDL_SYSTEM                  = $0025;          // GetSystemDirectory()
  CSIDL_PROGRAM_FILES           = $0026;          // C:\Program Files
  CSIDL_MYPICTURES              = $0027;          // C:\Program Files\My Pictures
  CSIDL_PROFILE                 = $0028;          // USERPROFILE
  CSIDL_SYSTEMX86               = $0029;          // x86 system directory on RISC
  CSIDL_PROGRAM_FILESX86        = $002a;          // x86 C:\Program Files on RISC
  CSIDL_PROGRAM_FILES_COMMON    = $002b;          // C:\Program Files\Common
  CSIDL_PROGRAM_FILES_COMMONX86 = $002c;          // x86 Program Files\Common on RISC
  CSIDL_COMMON_TEMPLATES        = $002d;          // All Users\Templates
  CSIDL_COMMON_DOCUMENTS        = $002e;          // All Users\Documents
  CSIDL_COMMON_ADMINTOOLS       = $002f;          // All Users\Start Menu\Programs\Administrative Tools
  CSIDL_ADMINTOOLS              = $0030;          // <user name>\Start Menu\Programs\Administrative Tools
  CSIDL_CONNECTIONS             = $0031;          // Network and Dial-up Connections
  CSIDL_COMMON_MUSIC            = $0035;          // All Users\My Music
  CSIDL_COMMON_PICTURES         = $0036;          // All Users\My Pictures
  CSIDL_COMMON_VIDEO            = $0037;          // All Users\My Video
  CSIDL_RESOURCES               = $0038;          // Resource Direcotry
  CSIDL_RESOURCES_LOCALIZED     = $0039;          // Localized Resource Direcotry
  CSIDL_COMMON_OEM_LINKS        = $003a;          // Links to All Users OEM specific apps
  CSIDL_CDBURN_AREA             = $003b;          // USERPROFILE\Local Settings\Application Data\Microsoft\CD Burning

  // unused                               0x003c
  CSIDL_COMPUTERSNEARME         = $003d;          // Computers Near Me (computered from Workgroup membership)
  CSIDL_FLAG_CREATE             = $8000;          // combine with CSIDL_ value to force folder creation in SHGetFolderPath()
  CSIDL_FLAG_DONT_VERIFY        = $4000;          // combine with CSIDL_ value to return an unverified folder path
  CSIDL_FLAG_DONT_UNEXPAND      = $2000;          // combine with CSIDL_ value to avoid unexpanding environment variables
  CSIDL_FLAG_NO_ALIAS           = $1000;          // combine with CSIDL_ value to insure non-alias versions of the pidl
  CSIDL_FLAG_PER_USER_INIT      = $0800;          // combine with CSIDL_ value to indicate per-user init (eg. upgrade)
  CSIDL_FLAG_MASK               = $FF00;          // mask for all possible flag values

파일 경로 얻어오기

path := ExtractFilePath(Application.exeName);

- end -

신고
TClientDataset 데이터를 XML로 가지고 왔지만,
일본어에 표현에 문제가 발견 되었다.

모든 문자열 데이터의 경우 fieldtype="string"로 사용했는데,
유니코드의 경우 fieldtype="string.uni" 라고
표현해야 TWideStringField로 인식하여 올바르게 데이터가 표현되지만,
영문만 있는경우 또 다시 문제가 발견되었다.

영문만 존재하는 경우 데이터를 모두 확인하여 fieldtype="string"로 했지만,
이것도 임시 방편일뿐 완벽한 처리는 되는 않는다.

TClientDataset 자체의 버그라고 생각되지만, 우선은 이렇게 처리 해두었다.

------------------------------------------------------------------------
FastReport 에도 다국어를 위해서 처리 해야 하는 문제가 발견되었다.
TfrxMemoView 속성에서 UseDefaultCharset 값을 True로 해야 일본어가 올바르게 표시 되었다.

관련 소스 위치

procedure TfrxCustomMemoView.GetData;
var
  i, j: Integer;
  s, s1, s2, dc1, dc2: WideString;
  ThLocale: Cardinal;
  LocCharset: Boolean;
begin
  inherited;
  ThLocale := 0;
  LocCharset := ((Font.Charset <> DEFAULT_CHARSET) and  not FUseDefaultCharset);
  if IsDataField then
  begin
    if DataSet.IsBlobField(DataField) then
    begin
      if LocCharset then
      begin
        ThLocale := GetThreadLocale;
        SetThreadLocale(GetLocalByCharSet(Font.Charset));
      end;
        DataSet.AssignBlobTo(DataField, FMemo);
      if LocCharset then
        SetThreadLocale(ThLocale);
    end
    else
    begin
      FValue := DataSet.Value[DataField];
      if FDisplayFormat.Kind = fkText then
      begin
        if LocCharset then
          FMemo.Text := AnsiToUnicode(AnsiString(DataSet.DisplayText[DataField]), Font.Charset)
     else

       FMemo.Text := DataSet.DisplayText[DataField];

      end
      else FMemo.Text := FormatData(FValue);
      if FHideZeros and (TVarData(FValue).VType <> varString) and
      {$IFDEF Delphi12}(TVarData(FValue).VType <> varUString) and{$ENDIF}
        (TVarData(FValue).VType <> varOleStr) and (FValue = 0) then
        FMemo.Text := '';
    end;
  end
신고

XLSReadWriteII4 : 몇 가지 설정

Programming/Delphi 2011.11.13 15:35 Posted by 파란크리스마스
행추가
ws.InsertRows(row+1, 1);

행삭제
ws.DeleteRows(row, row+4);

셀병합
ws.MergeCells(1, p_row, 1, row-1);

테두리     
ws.Range.ItemsRef['A'+inttostr(2)+':'+'A'+inttostr(row)].BorderOutlineStyle := cbsThin; // cbsHair;

가운데 설정
ws.Cell[9, row].HorizAlignment := chaCenter;

몇 가지 설정
ws.Cell[i, row].NumberFormat := '_-* #,##0_-;-* #,##0_-;_-* ""-""_-;_-@_-';
ws.Cell[9, row].NumberFormat := '0%';

셀높이 설정
ws.Rows[(i*28)+2].Height := ws.Rows[2].Height;

셀복사
XLS01.CopyCells(SheetIndex, 0,0,7,27, SheetIndex, 0,(i*28));

출력 설정
XLS01.Sheet[SheetIndex].PrintSettings.Options := [psoHorizCenter];
XLS01.Sheet[SheetIndex].PrintSettings.HorizPagebreaks.Clear;
//
HorizPagebreak := ws.PrintSettings.HorizPagebreaks.Add;
HorizPagebreak.Row := (loopRow*28)+addRow-tmpAddRow-1;

배경색 지정

function RGBToColor(R,G,B:Byte): TColor;
begin
Result:=B Shl 16 Or
G Shl 8 Or
R;
end;

color := RGBToColor(255,255,0)
ws.Range.ItemsRef['A'+IntToStr(row)+':'+GetRowStr(col)+IntToStr(row)].FillPatternForeColor := TColorToClosestXColor(color);
신고

Delphi tip - 시스템 임시 폴더 구하기

Programming/Delphi 2011.02.19 14:22 Posted by 파란크리스마스
출처 : http://www.delphitricks.com/source-code/systeminfo/get_windows_system_temporary_directory.html

{ Getting the Temporary Directory } 

function GetTempDir: string; 
var 
  Buffer: array[0..MAX_PATH] of Char; 
begin 
  GetTempPath(SizeOf(Buffer) - 1, Buffer); 
  Result := StrPas(Buffer); 
end; 

function GetTempPath: string; 
var 
  TmpDir: PChar; 
begin 
  TmpDir := StrAlloc(MAX_PATH); 
  GetTempPath(TmpDir, MAX_PATH); 
  Result := string(TmpDir); 
  if Result[Length(Result)] <> '\' then 
    Result := Result + '\'; 
  StrDispose(TmpDir); 
end; 

function GetTempPath(var S: String): Boolean; 
var 
  Len: Integer; 
begin 
  Len := Windows.GetTempPath(0, nil); 
  if Len > 0 then 
  begin 
    SetLength(S, Len); 
    Len := Windows.GetTempPath(Len, PChar(S)); 
    SetLength(S, Len); 
    Result := Len > 0; 
  end else 
    Result := False; 
end; 
신고

Delphi - TcxVirtualTreeList

Programming/Delphi 2010.12.05 00:49 Posted by 파란크리스마스
- CustomDataSource 사용시 동적인 Count 사용
OptionsData.SmartLoad := True;

- 트리노드의 초기 + 표시
OptionsData.CheckHasChildren := false;
신고


 

티스토리 툴바