micro:bit - Camera (LS-Y201) image writing to SD

OS/micro:bit 2018.06.17 13:02 Posted by 파란크리스마스

출처

Camera (LS-Y201)

micro:bit를 이용해서 카메라로 입력받은 이미지 데이터를 SD 메모리에 저장해보았습니다.

소스

//#include "MicroBit.h"
//#include "MicroBitSerial.h"
#include "Camera_LS_Y201.h"
#include "SDFileSystem.h"

#define DEBMSG      printf
#define NEWLINE()   printf("\r\n")
#define FILENAME    "/sd/IMG_%04d.jpg"

SDFileSystem sd(P0_21, P0_22, P0_23, P0_16, "sd"); // mosi, miso, sclk, cs
Camera_LS_Y201 cam1(P0_2, P0_3);
//MicroBitSerial serial(USBTX, USBRX);

typedef struct work {
    FILE *fp;
} work_t;
 
work_t work;
 
/**
 * Callback function for readJpegFileContent.
 *
 * @param buf A pointer to a buffer.
 * @param siz A size of the buffer.
 */
void callback_func(int done, int total, uint8_t *buf, size_t siz) {
    fwrite(buf, siz, 1, work.fp);
 
    static int n = 0;
    int tmp = done * 100 / total;
    if (n != tmp) {
        n = tmp;
        DEBMSG("Writing...: %3d%%", n);
        NEWLINE();
    }
}
 
/**
 * Capture.
 *
 * @param cam A pointer to a camera object.
 * @param filename The file name.
 *
 * @return Return 0 if it succeed.
 */
int capture(Camera_LS_Y201 *cam, char *filename) {
    /*
     * Take a picture.
     */
    if (cam->takePicture() != 0) {
        return -1;
    }
    DEBMSG("Captured.");
    NEWLINE();
 
    /*
     * Open file.
     */
    work.fp = fopen(filename, "wb");
    if (work.fp == NULL) {
        return -2;
    }
 
    /*
     * Read the content.
     */
    DEBMSG("%s", filename);
    NEWLINE();
    if (cam->readJpegFileContent(callback_func) != 0) {
        fclose(work.fp);
        return -3;
    }
    fclose(work.fp);
 
    /*
     * Stop taking pictures.
     */
    cam->stopTakingPictures();
 
    return 0;
}

int main() {
	  DEBMSG("Camera module");
	  NEWLINE();
	  DEBMSG("Resetting...");
	  NEWLINE();
	  wait(1);

	  if (cam1.reset() == 0) {
	      DEBMSG("Reset OK.");
	      NEWLINE();
	  } else {
	      DEBMSG("Reset fail.");
	      NEWLINE();
	      error("Reset fail.");
	  }
	  wait(1);

	  int cnt = 0;
	  while (1) {
	      char fname[64];
	      snprintf(fname, sizeof(fname) - 1, FILENAME, cnt);
	      int r = capture(&cam1, fname);
	      if (r == 0) {
	          DEBMSG("[%04d]:OK.", cnt);
	          NEWLINE();
	      } else {
	          DEBMSG("[%04d]:NG. (code=%d)", cnt, r);
	          NEWLINE();
	          error("Failure.");
	      }
	      cnt++;
	  }
}

HEX 파일

pulse-combined.zip

실행

yotta 설치

OS/micro:bit 2018.06.16 04:15 Posted by 파란크리스마스

출처

yotta 설치

python.exe -m pip install --upgrade pip==9.0.3
pip install --upgrade setuptools
pip install -I -U yotta

환경변수 설정 (run_yotta.bat c:\yotta 명령으로 설정 가능)

YOTTA_INSTALL_LOCATION=C:\yotta
YOTTA_PATH=;C:\yotta;C:\yotta\gcc\bin;C:\yotta\python;C:\yotta\python\Scripts;C:\yotta\cmake-3.4.0-rc3-win32-x86\bin;C:\yotta\git-scm\bin;C:\yotta\mercurial\bin;
PATH=C:\yotta;C:\yotta\python\;C:\yotta\python\Scripts;C:\yotta\cmake-3.4.0-rc3-win32-x86\bin;%PATH%

개발환경 만들기

D:\>run_yotta.bat
(workspace) D:\>mkdir pulse
(workspace) D:\>cd pulse
(workspace) D:\pulse>yotta init
(workspace) D:\pulse>yotta target bbc-microbit-classic-gcc
(workspace) D:\pulse>yotta install lancaster-university/microbit

main.cpp

#include "MicroBit.h" 
 
MicroBit uBit;  
 
int main() { 
  uBit.init(); 
  uBit.display.scroll("http://bluexmas.tistory.com"); 
  release_fiber(); 
}

빌드 - hex 파일 생성

(workspace) D:\pulse>yotta build

실행

pulse-combined.hex 파일 마이크로 비트에 복사

micro:bit - pxt 설치(오프라인 블럭 컴파일러 구축)

OS/micro:bit 2018.04.07 22:45 Posted by 파란크리스마스

출처

windows-build-tools 설치(관리자모드)

출처 : Thinker :: error MSB3428: Visual C++ 구성 요소 "VCBuild.exe"을(를) 로드할 수 ...

C:\WINDOWS\system32>npm install --global --production windows-build-tools

> windows-build-tools@3.0.1 postinstall C:\Users\bluesanta\AppData\Roaming\npm\node_modules\windows-build-tools
> node ./dist/index.js

Downloading BuildTools_Full.exe
[============================================>] 100.0% of 3.29 MB (3.29 MB/s)
Downloaded BuildTools_Full.exe. Saved to C:\Users\bluesanta\.windows-build-tools\BuildTools_Full.exe.

Starting installation...
Launched installers, now waiting for them to finish.
This will likely take some time - please be patient!

Status from the installers:
---------- Visual Studio Build Tools ----------
---------- Visual Studio Build Tools ----------
Successfully installed Visual Studio Build Tools.
------------------- Python --------------------
Python 2.7.15 is already installed, not installing again.

All done!

+ windows-build-tools@3.0.1
added 141 packages in 310.658s

pxt 관련 라이브러리 설치

D:\microbit>npm install -g jake
C:\Users\bluesanta\AppData\Roaming\npm\jake -> C:\Users\bluesanta\AppData\Roaming\npm\node_modules\jake\bin\cli.js
+ jake@8.0.16
added 13 packages in 2.485s

D:\microbit>npm install -g typings
npm WARN deprecated typings@2.1.1: Typings is deprecated in favor of NPM @types -- see README for more information
C:\Users\bluesanta\AppData\Roaming\npm\typings -> C:\Users\bluesanta\AppData\Roaming\npm\node_modules\typings\dist\bin.js
+ typings@2.1.1
added 183 packages in 12.988s

pxt 다운로드

D:\microbit>git clone https://github.com/microsoft/pxt
Cloning into 'pxt'...
remote: Counting objects: 52887, done.
remote: Compressing objects: 100% (424/424), done.
remote: Total 52887 (delta 311), reused 324 (delta 173), pack-reused 52279
Receiving objects: 100% (52887/52887), 131.47 MiB | 197.00 KiB/s, done.
Resolving deltas: 100% (37029/37029), done.

D:\microbit>cd pxt

D:\microbit\pxt>git checkout v0
Switched to a new branch 'v0'
Branch 'v0' set up to track remote branch 'v0' from 'origin'.

pxt 설치

D:\microbit\pxt>npm install npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3 (node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"}) added 115 packages in 12.661s D:\microbit\pxt>typings install D:\microbit\pxt>jake D:\microbit\pxt>cd ../ D:\microbit>

pxt-microbit 설치

D:\microbit>git clone https://github.com/microsoft/pxt-microbit
D:\microbit>cd pxt-microbit
D:\microbit\pxt-microbit>npm install -g pxt
D:\microbit\pxt-microbit>npm install
D:\microbit\pxt-microbit>npm link ../pxt
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

added 115 packages in 21.441s
C:\server\node-v8.9.1-win-x64\node_modules\pxt-core -> D:\microbit\pxt
D:\microbit\pxt-microbit\node_modules\pxt-core -> C:\server\node-v8.9.1-win-x64\node_modules\pxt-core -> D:\microbit\pxt

pxt 서버 실행

(workspace) D:\>mkdir pxtsrc

(workspace) D:\>cd pxtsrc

(workspace) D:\pxtsrc>pxt target microbit
Installing pxt-microbit locally; don't worry about package.json warnings.

> keytar@4.2.1 install D:\pxtsrc\node_modules\keytar
> prebuild-install || node-gyp rebuild

prebuild-install info begin Prebuild-install version 2.5.1
prebuild-install info looking for local prebuild @ prebuilds\keytar-v4.2.1-node-v57-win32-x64.tar.gz
prebuild-install info looking for cached prebuild @ C:\Users\bluesanta\AppData\Roaming\npm-cache\_prebuilds\https-github.com-atom-node-keytar-releases-download-v4.2.1-keytar-v4.2.1-node-v57-win32-x64.tar.gz
prebuild-install info found cached prebuild
prebuild-install info unpacking @ C:\Users\bluesanta\AppData\Roaming\npm-cache\_prebuilds\https-github.com-atom-node-keytar-releases-download-v4.2.1-keytar-v4.2.1-node-v57-win32-x64.tar.gz
prebuild-install info unpack resolved to D:\pxtsrc\node_modules\keytar\build\Release\keytar.node
prebuild-install info unpack required D:\pxtsrc\node_modules\keytar\build\Release\keytar.node successfully
prebuild-install info install Successfully installed prebuilt binary!

> node-hid@0.5.7 install D:\pxtsrc\node_modules\node-hid
> prebuild-install || node-gyp rebuild

prebuild-install info begin Prebuild-install version 2.5.1
prebuild-install info looking for local prebuild @ prebuilds\node-hid-v0.5.7-node-v57-win32-x64.tar.gz
prebuild-install info looking for cached prebuild @ C:\Users\bluesanta\AppData\Roaming\npm-cache\_prebuilds\https-github.com-node-hid-node-hid-releases-download-v0.5.7-node-hid-v0.5.7-node-v57-win32-x64.tar.gz
prebuild-install info found cached prebuild
prebuild-install info unpacking @ C:\Users\bluesanta\AppData\Roaming\npm-cache\_prebuilds\https-github.com-node-hid-node-hid-releases-download-v0.5.7-node-hid-v0.5.7-node-v57-win32-x64.tar.gz
prebuild-install info unpack resolved to D:\pxtsrc\node_modules\node-hid\build\Release\HID.node
prebuild-install info unpack required D:\pxtsrc\node_modules\node-hid\build\Release\HID.node successfully
prebuild-install info install Successfully installed prebuilt binary!

> serialport@6.1.1 install D:\pxtsrc\node_modules\serialport
> prebuild-install || node-gyp rebuild

prebuild-install info begin Prebuild-install version 2.5.1
prebuild-install info looking for local prebuild @ prebuilds\serialport-v6.1.1-node-v57-win32-x64.tar.gz
prebuild-install info looking for cached prebuild @ C:\Users\bluesanta\AppData\Roaming\npm-cache\_prebuilds\https-github.com-node-serialport-node-serialport-releases-download-v6.1.1-serialport-v6.1.1-node-v57-win32-x64.tar.gz
prebuild-install info found cached prebuild
prebuild-install info unpacking @ C:\Users\bluesanta\AppData\Roaming\npm-cache\_prebuilds\https-github.com-node-serialport-node-serialport-releases-download-v6.1.1-serialport-v6.1.1-node-v57-win32-x64.tar.gz
prebuild-install info unpack resolved to D:\pxtsrc\node_modules\serialport\build\Release\serialport.node
prebuild-install info unpack required D:\pxtsrc\node_modules\serialport\build\Release\serialport.node successfully
prebuild-install info install Successfully installed prebuilt binary!
npm WARN saveError ENOENT: no such file or directory, open 'D:\pxtsrc\package.json'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open 'D:\pxtsrc\package.json'
npm WARN pxtsrc No description
npm WARN pxtsrc No repository field.
npm WARN pxtsrc No README data
npm WARN pxtsrc No license field.

+ pxt-microbit@0.14.30
added 384 packages in 15.705s
Installed PXT/microbit. To start server run:
    pxt serve

(workspace) D:\pxtsrc>pxt serve
Using target PXT/microbit with build engine yotta
  Target dir:   D:\pxtsrc\node_modules\pxt-microbit
  PXT Core dir: D:\pxtsrc\node_modules\pxt-core
Invalid accessToken format, expecting something like 'https://example.com/?access_token=0abcd.XXXX'
Going to D:\pxtsrc\node_modules\pxt-microbit
No sim/tsconfig.json; assuming npm installed package
Starting server in D:\pxtsrc\node_modules\pxt-microbit
With pxt core at D:\pxtsrc\node_modules\pxt-core
starting local ws server at 3233...
serial: monitoring ports...
---------------------------------------------

To launch the editor, open this URL:
http://localhost:3232/#local_token=452b727d-6d77-4d83-98d5-0bdab305f72e&wsport=3233

---------------------------------------------
opening http://localhost:3232/#local_token=452b727d-6d77-4d83-98d5-0bdab305f72e&wsport=3233

프로젝트 생성

D:\pxtsrc\projects>mkdir pxt-ultrasonic-microbit

D:\pxtsrc\projects>cd pxt-ultrasonic-microbit

D:\pxtsrc\projects\pxt-ultrasonic-microbit>pxt init
Using target PXT/microbit with build engine yotta
  Target dir:   D:\pxtsrc\node_modules\pxt-microbit
  PXT Core dir: D:\pxtsrc\node_modules\pxt-core
Invalid accessToken format, expecting something like 'https://example.com/?access_token=0abcd.XXXX'
name [ultrasonic-microbit]:
description []:
license [MIT]:
skipping download of local pkg: file:.
Package initialized.
Try 'pxt add' to add optional features.

D:\pxtsrc\projects\pxt-ultrasonic-microbit>code .

빌드

micro:bit - 라인 트레이서(Line Trace Sensor)

OS/micro:bit 2018.03.18 17:01 Posted by 파란크리스마스

출처 : Motor Driver Board for the BBC micro:bit - V2 | Kitronik
Blog Yamasho: Delphi 10.2.2:Bleで Microbitと通信する。
googlesamples/android-BluetoothLeGatt - GitHub
ButtonService - micro:bit runtime
microbit-samples/source/examples/bluetooth-services/main.cpp - GitHub
https://github.com/lancaster-university/microbit-dal/issues/337
Advanced - micro:bit runtime - GitHub Pages
Send/Receive Data Using BLE and MBED | BBC:Microbit - Instructables

micro:bit - 라인 트레이서(Line Trace Sensor)

라인트레이서 센서와 초음파 거리센서(HC-SR04)를 이용해서 라인을 따라서 가면서 장애물이 있으면 멈추는 RC카를 구현했습니다.

소스

#include "MicroBit.h"
#include "MicroBitSerial.h"
#include "hcsr04.h"

//MicroBit uBit;
MicroBitSerial serial(USBTX, USBRX);
HCSR04 usensor(P0_0, P0_30); // P0_0 TRIGGER P0_30 ECHO
unsigned int dist;

//
// P0_1, P0_26, P0_17 성공 - line
// P0_18, P0_20, P0_3, P0_16 - moter

//AnalogIn ain(P0_3);
DigitalIn LINE_T1(P0_1);
DigitalIn LINE_T2(P0_23);
DigitalIn LINE_T3(P0_21);
DigitalIn LINE_T4(P0_22);

int main() {
	//uBit.init();
	//uBit.display.scroll("init", 70);
	serial.printf("init : \r\n");
	 
	while(1) {
		usensor.start();
		wait_ms(500);
		dist = usensor.get_dist_cm();
		serial.printf("-------------------------\r\n d:%d\r\n", dist);
		
		/*
		float x = ain.read();
		int aa = (int)(x *  1000);
		serial.printf("%d \r\n", aa);
		*/

		serial.printf("1:%d - ", LINE_T1.read());
		serial.printf("2:%d - ", LINE_T2.read());
		serial.printf("3:%d - ", LINE_T3.read());

		if (LINE_T4 == 1) {
			serial.printf("4:1\r\n");
		} else {
			serial.printf("4:0\r\n");
		}
	}
}

콘솔 로그

소스 - micro:bit - RC Car - Line Trace Sensor

source.zip

#include "MicroBit.h"
#include "MicroBitSerial.h"
#include "hcsr04.h"

MicroBit uBit;
//MicroBitSerial serial(USBTX, USBRX);
HCSR04 usensor(P0_3, P0_2); // P0_0 TRIGGER P0_30 ECHO
unsigned int dist;

//
// P0_1, P0_26, P0_17 성공 - line
// P0_18, P0_20, P0_3, P0_16 - moter

//AnalogIn ain(P0_3);
DigitalIn LINE_T1(P0_1);
DigitalIn LINE_T2(P0_23);
DigitalIn LINE_T3(P0_21);
DigitalIn LINE_T4(P0_22);

#define MOTER_LOW            0
#define MOTER_HIGH           0.32 // 스피드 - 0 ~ 1 | 최대속도 = 1
 
PwmOut moter_right_front(P0_18);    //12 - right
PwmOut moter_right_back(P0_20);     //8
PwmOut moter_left_front(P0_3);      //16 - left
PwmOut moter_left_back(P0_16);          //0
 
//모터A,B 정회전
void bothMotorStart()
{
  moter_right_front = MOTER_HIGH;
  moter_right_back = MOTER_LOW;
  moter_left_front = MOTER_HIGH;
  moter_left_back = MOTER_LOW;
}
  
//모터A,B 역회전
void bothMotorBack()
{
  moter_right_front = MOTER_LOW;
  moter_right_back = MOTER_HIGH;
  moter_left_front = MOTER_LOW;
  moter_left_back = MOTER_HIGH;
}
    
//모터A,B Stop
void stopAllMotor()
{
  moter_right_front = MOTER_LOW;
  moter_right_back = MOTER_LOW;
  moter_left_front = MOTER_LOW;
  moter_left_back = MOTER_LOW;
}
    
//모터A 역회전, 모터B 정회전
void turnLeft()
{
  moter_right_front = MOTER_LOW;
  moter_right_back = MOTER_HIGH;
  moter_left_front = MOTER_HIGH;
  moter_left_back = MOTER_LOW;
}
    
//모터A 정회전, 모터B 역회전
void turnRight()
{
  moter_right_front = MOTER_HIGH;
  moter_right_back = MOTER_LOW;
  moter_left_front = MOTER_LOW;
  moter_left_back = MOTER_HIGH;
}
    
//모터A 정회전, 모터B Stop
void motorA_Rotation()
{
  moter_right_front = MOTER_HIGH;
  moter_right_back = MOTER_LOW;
  moter_left_front = MOTER_LOW;
  moter_left_back = MOTER_LOW;
}
    
//모터A Stop, 모터B 정회전
void motorB_Rotation()
{
  moter_right_front = MOTER_LOW;
  moter_right_back = MOTER_LOW;
  moter_left_front = MOTER_HIGH;
  moter_left_back = MOTER_LOW;
}
    
//모터A 역회전, 모터B Stop
void motorA_Reverse()
{
  moter_right_front = MOTER_LOW;
  moter_right_back = MOTER_HIGH;
  moter_left_front = MOTER_LOW;
  moter_left_back = MOTER_LOW;
}
    
//모터A Stop, 모터B 역회전
void motorB_Reverse()
{
  moter_right_front = MOTER_LOW;
  moter_right_back = MOTER_LOW;
  moter_left_front = MOTER_LOW;
  moter_left_back = MOTER_HIGH;
}

int main() {
	uBit.init();
	uBit.display.scroll("init", 70);
	uBit.serial.printf("init : \r\n");
	 
	while(1) {
		usensor.start();
		wait_ms(50);
		dist = usensor.get_dist_cm();
		uBit.serial.printf("-------------------------\r\n d:%d\r\n", dist);
		uBit.serial.printf("%d, %d, %d, %d\r\n", LINE_T1.read(),LINE_T2.read(),LINE_T3.read(),LINE_T4.read());

		if (dist <= 10) {
			stopAllMotor();
		} else {
			if (LINE_T2 == 1 || LINE_T3 == 1) {
				bothMotorStart();
			} else if (LINE_T1 == 1) {
				turnRight();
			} else if (LINE_T4 == 1) {
				turnLeft();
			} else {
				bothMotorStart();
			}
		}

	}
}

micro:bit - RC Car - Line Trace Sensor

micro:bit - 초음파 거리센서(HC-SR04)

OS/micro:bit 2018.03.15 00:18 Posted by 파란크리스마스

출처 : Steve136/microbit-ultrasonic: Example usage of a HC-SR04 Ultrasonic Sensor and the BBC Micro:Bit.
HCSR04 - Ultrasound Ranging Sensor module | Mbed

micro:bit - 초음파 거리센서(HC-SR04)

 

소스

#include "MicroBit.h"
#include "hcsr04.h"

MicroBit uBit;
HCSR04 usensor(P0_3, P0_2); // TRIGGER, ECHO
unsigned int dist;

int main() {
	uBit.init();
	uBit.display.scroll("init", 70);
	
	while(1) {
		usensor.start();
		wait_ms(500); 
		dist = usensor.get_dist_cm();
		
		char buf[100];
		sprintf (buf, "d:%d", dist);
		uBit.display.scroll(buf, 70);
		wait(1.0); // 1 sec  
	}
}

micro:bit - SD Card File 생성 및 쓰기

OS/micro:bit 2018.02.25 20:56 Posted by 파란크리스마스

출처 : SD Card File System - Cookbook | Mbed
FATFileSystem - FATFileSystem | Mbed

micro:bit - SD Card File 생성 및 쓰기

SD Card File System와 FATFileSystem 라이브러리를 사용해서 micro:bit에서 마이크로 SD에 파일 쓰기 예제를 만들어 보았습니다.
Microsoft Block용 라이브러리인 pxt-microsd-microbit도 공개 되어 있으니 참고 하세요.

소스

#include "MicroBit.h"
#include "SDFileSystem.h"

MicroBit uBit;

SDFileSystem sd(P0_21, P0_22, P0_23, P0_16, "sd"); // mosi, miso, sclk, cs

int main() {
	//uBit.init();
	
	//디렉토리 생성
	//mkdir("/sd/mydir", 0777);
	
	// 파일 열기
	FILE *fp = fopen("/sd/microbit.txt", "w");
	if(fp == NULL) {
		error("Could not open file for write\n");
	}
	// 파일 쓰기
	fprintf(fp, "Hello World!\n");
	// 파일 닫기
	fclose(fp);
}

micro:bit - 이벤트

OS/micro:bit 2018.02.24 11:32 Posted by 파란크리스마스

MicroBitRadioEvent.h

    /**
      * Associates the given event with the radio channel.
      *
      * Once registered, all events matching the given registration sent to this micro:bit's
      * default EventModel will be automatically retransmitted on the radio.
      *
      * @param id The id of the event to register.
      *
      * @param value the value of the event to register.
      *
      * @return MICROBIT_OK on success, or MICROBIT_NO_RESOURCES if no default EventModel is available.
      *
      * @note The wildcards MICROBIT_ID_ANY and MICROBIT_EVT_ANY can also be in place of the
      *       id and value fields.
      */
    int listen(uint16_t id, uint16_t value);

    /**
      * Associates the given event with the radio channel.
      *
      * Once registered, all events matching the given registration sent to the given
      * EventModel will be automatically retransmitted on the radio.
      *
      * @param id The id of the events to register.
      *
      * @param value the value of the event to register.
      *
      * @param eventBus The EventModel to listen for events on.
      *
      * @return MICROBIT_OK on success.
      *
      * @note The wildcards MICROBIT_ID_ANY and MICROBIT_EVT_ANY can also be in place of the
      *       id and value fields.
      */
    int listen(uint16_t id, uint16_t value, EventModel &eventBus);

MicroBitMessageBus.cpp

/**
  * Queues the given event to be sent to all registered recipients.
  *
  * @param evt The event to send.
  *
  * @code
  * MicroBitMessageBus bus;
  *
  * // Creates and sends the MicroBitEvent using bus.
  * MicrobitEvent evt(MICROBIT_ID_BUTTON_A, MICROBIT_BUTTON_EVT_CLICK);
  *
  * // Creates the MicrobitEvent, but delays the sending of that event.
  * MicrobitEvent evt1(MICROBIT_ID_BUTTON_A, MICROBIT_BUTTON_EVT_CLICK, CREATE_ONLY);
  *
  * bus.send(evt1);
  *
  * // This has the same effect!
  * evt1.fire()
  * @endcode
  */
int MicroBitMessageBus::send(MicroBitEvent evt)
{
    // We simply queue processing of the event until we're scheduled in normal thread context.
    // We do this to avoid the possibility of executing event handler code in IRQ context, which may bring
    // hidden race conditions to kids code. Queuing all events ensures causal ordering (total ordering in fact).
    this->queueEvent(evt);
    return MICROBIT_OK;
}

MicroBitFiber.cpp

/**
  * Blocks the calling thread until the specified event is raised.
  * The calling thread will be immediateley descheduled, and placed onto a
  * wait queue until the requested event is received.
  *
  * @param id The ID field of the event to listen for (e.g. MICROBIT_ID_BUTTON_A)
  *
  * @param value The value of the event to listen for (e.g. MICROBIT_BUTTON_EVT_CLICK)
  *
  * @return MICROBIT_OK, or MICROBIT_NOT_SUPPORTED if the fiber scheduler is not running, or associated with an EventModel.
  *
  * @code
  * fiber_wait_for_event(MICROBIT_ID_BUTTON_A, MICROBIT_BUTTON_EVT_CLICK);
  * @endcode
  *
  * @note the fiber will not be be made runnable until after the event is raised, but there
  * are no guarantees precisely when the fiber will next be scheduled.
  */
int fiber_wait_for_event(uint16_t id, uint16_t value)
{
    int ret = fiber_wake_on_event(id, value);

    if(ret == MICROBIT_OK)
        schedule();

	return ret;
}

/**
  * Configures the fiber context for the current fiber to block on an event ID
  * and value, but does not deschedule the fiber.
  *
  * @param id The ID field of the event to listen for (e.g. MICROBIT_ID_BUTTON_A)
  *
  * @param value The value of the event to listen for (e.g. MICROBIT_BUTTON_EVT_CLICK)
  *
  * @return MICROBIT_OK, or MICROBIT_NOT_SUPPORTED if the fiber scheduler is not running, or associated with an EventModel.
  *
  * @code
  * fiber_wake_on_event(MICROBIT_ID_BUTTON_A, MICROBIT_BUTTON_EVT_CLICK);
  *
  * //perform some time critical operation.
  *
  * //deschedule the current fiber manually, waiting for the previously configured event.
  * schedule();
  * @endcode
  */
int fiber_wake_on_event(uint16_t id, uint16_t value)
{
    Fiber *f = currentFiber;

	if (messageBus == NULL || !fiber_scheduler_running())
		return MICROBIT_NOT_SUPPORTED;

    // Sleep is a blocking call, so if we're in a fork on block context,
    // it's time to spawn a new fiber...
    if (currentFiber->flags & MICROBIT_FIBER_FLAG_FOB)
    {
        // Allocate a TCB from the new fiber. This will come from the tread pool if availiable,
        // else a new one will be allocated on the heap.
        forkedFiber = getFiberContext();

        // If we're out of memory, there's nothing we can do.
        // keep running in the context of the current thread as a best effort.
        if (forkedFiber != NULL)
        {
            f = forkedFiber;
            dequeue_fiber(f);
            queue_fiber(f, &runQueue);
            schedule();
        }
    }

    // Encode the event data in the context field. It's handy having a 32 bit core. :-)
    f->context = value << 16 | id;

    // Remove ourselves from the run queue
    dequeue_fiber(f);

    // Add ourselves to the sleep queue. We maintain strict ordering here to reduce lookup times.
    queue_fiber(f, &waitQueue);

    // Register to receive this event, so we can wake up the fiber when it happens.
    // Special case for the notify channel, as we always stay registered for that.
    if (id != MICROBIT_ID_NOTIFY && id != MICROBIT_ID_NOTIFY_ONE)
        messageBus->listen(id, value, scheduler_event, MESSAGE_BUS_LISTENER_IMMEDIATE);

    return MICROBIT_OK;
}

이벤트 메소드 구현

void onButtonA(MicroBitEvent e)
{
  uBit.display.scroll("A");
}

리스너 등록

  // listen for user button interactions
  uBit.messageBus.listen(MICROBIT_ID_BUTTON_A, MICROBIT_BUTTON_EVT_CLICK, onButtonA);
  uBit.messageBus.listen(MICROBIT_ID_BUTTON_B, MICROBIT_BUTTON_EVT_CLICK, onButtonB);
  uBit.messageBus.listen(MICROBIT_ID_BUTTON_AB, MICROBIT_BUTTON_EVT_CLICK, onButtonAB);

micro:bit - ESP8266 ESP-01 Serial Wireless WIFI Module

OS/micro:bit 2018.02.23 23:31 Posted by 파란크리스마스

출처 : micro:bit IoT In C - Getting On WiFi

micro:bit - ESP8266 ESP-01 Serial Wireless WIFI Module

pulse-combined.hex

micro:bit의 한가지 아쉬운 점은 Wifi가 내장되어 있지 않아 Wifi를 따로 설치해야 되는데, 이번에 아두이노에서 많이 사용하는 Wifi 모듈인 ESP8266을 사용해서 공유기에 접속하고 간단하게 웹서비스로 온도를 제공하는 서비스를 구현했습니다. 

결과는 PC 브라우져로 접속하면 결과를 확인 해볼 수 있습니다.

배선

핀 배열

  1. Ground - connect to ground 
  2. TXO - the serial tx pin 
  3. GPIO2 - ignore 
  4. CHPD - chip enable connect to 3.3V 
  5. GPIO0 - ignore 
  6. RST - reset leave unconnected 
  7. RXI - the serial rx pin 
  8. VDD - Supply voltage connect to 3.3V

소스

#include "MicroBit.h" 

MicroBit uBit;

void initWiFi();
int ATWiFi();
int resetWiFi();
int setUARTWiFi();
int scanWiFi();
int getIPWiFi(); 
int modeWiFi(int mode);
int connectWiFi(ManagedString ssid, ManagedString pass); int getWebPageWiFi(ManagedString URL, ManagedString page); 
int getVersionWiFi(); 
int startServerWiFi(); 
int waitForWiFi(ManagedString target, int retry, int pause);
int find(ManagedString c, ManagedString s);
void debug(ManagedString s);

#define Tx MICROBIT_PIN_P0 
#define Rx MICROBIT_PIN_P1 
#define DEBUG 1

int main() { 
	uBit.init();
	initWiFi();
	modeWiFi(1);
	connectWiFi("ssid", "password");
	getIPWiFi();
	startServerWiFi();
	release_fiber();
}

void initWiFi() { 
	uBit.serial.redirect(Tx, Rx);
	uBit.serial.baud(115200);
	uBit.serial.setRxBufferSize(500);
}

int ATWiFi() {
	uBit.serial.send("AT\r\n", SYNC_SPINWAIT);
	return waitForWiFi("OK", 150, 10); 
}

int getVersionWiFi() {
	uBit.serial.send("AT+GMR\r\n", SYNC_SPINWAIT);
	return waitForWiFi("OK", 200, 10);
}

int resetWiFi() { 
	uBit.serial.send("AT+RST\r\n", SYNC_SPINWAIT);
	return waitForWiFi("OK", 1000, 10);
}

int setUARTWiFi() { 
	uBit.serial.send("AT+UART_CUR=115200,8,1,0,0\r\n", SYNC_SPINWAIT);
	return waitForWiFi("OK", 200, 10);
}

int scanWiFi() {
	uBit.serial.send("AT+CWLAP\r\n", SYNC_SPINWAIT);
	return waitForWiFi("OK", 500, 50);
}

int modeWiFi(int mode) {
	ManagedString cmd = "AT+CWMODE_CUR=" + ManagedString(mode) + "\r\n";
	uBit.serial.send(cmd, SYNC_SPINWAIT);
	return waitForWiFi("OK", 200, 10); 
}

int connectWiFi( ManagedString ssid, ManagedString pass) { 
	ManagedString cmd = "AT+CWJAP_CUR=\"" + ssid + "\",\"" + pass + "\"\r\n";
	uBit.serial.send(cmd, SYNC_SPINWAIT);
	return waitForWiFi("OK", 200, 20);
}

int getIPWiFi() {
	uBit.serial.send("AT+CIFSR\r\n", SYNC_SPINWAIT);
	return waitForWiFi("OK", 200, 10);
}

int getWebPageWiFi(ManagedString URL, ManagedString page) {
	ManagedString cmd = "AT+CIPSTART=\"TCP\",\"" + URL + "\",80\r\n";
	uBit.serial.send(cmd, SYNC_SPINWAIT);
	
	if (waitForWiFi("OK", 100, 20) == 0) 
		return 0;
		
	ManagedString http = "GET " + page + " HTTP/1.0\r\nHost:" + URL + "\r\n\r\n";
	cmd = "AT+CIPSEND=" +  ManagedString(http.length()) + "\r\n"; 
	uBit.serial.send(cmd, SYNC_SPINWAIT); 
	
	int retry; 
	ManagedString s;
	s = "";
	retry = 40;
	
	do {
		uBit.sleep(100);
		s = s + uBit.serial.read(500, ASYNC); 
		retry--;
	} while (find(">", s) == 0 && retry != 0);
	
	uBit.serial.send(http, SYNC_SPINWAIT);
	retry = 100; 
	
	do { 
		uBit.sleep(100);
		s = s + uBit.serial.read(500, ASYNC);
		retry--;
	} while (s.length() < 500 && retry != 0);
	
	if (DEBUG)debug("\n\rPage\n\r" + s + "\n\r");
	return 1; 
}

int startServerWiFi() {  
	uBit.serial.send("AT+CIPMUX=1\r\n", SYNC_SPINWAIT);
	if (waitForWiFi("OK", 100, 20) == 0) return 0; 
	uBit.serial.send("AT+CIPSERVER=1,80\r\n", 
	                                  SYNC_SPINWAIT);
	if (waitForWiFi("OK", 100, 20) == 0) return 0;
	ManagedString s;
	for (;;) {
		s="";
		do {
		 uBit.sleep(100);
		 if(s>500)s=""; 
		 s = uBit.serial.read(500, ASYNC);
		} while (find("+IPD", s) == 0);
	
		if (DEBUG)debug("\n\rClient Connected\n\r" + s + "\n\r");
			
		int b = find("+IPD", s);
		s = s.substring(b + 1, s.length());
		b = find(",", s); 
		s = s.substring(b + 1, s.length());
		b = find(",", s);
		ManagedString id = s.substring(0, b);
		
		if (DEBUG)debug("\n\rTCP id:" + id + "\n\r"); 
			
		ManagedString headers = "HTTP/1.0 200 OK\r\n";
		headers = headers + "Server: micro:bit\r\n"; 
		headers = headers + "Content-type: text/html\r\n\r\n";
		// ManagedString html = "<html><head><title>Temperature</title></head><body>{\"humidity\":82%,\"airtemperature\":23.5C}</p></body></html>\r\n";
		
		char html [100];
		sprintf (html, "<html><head><title>Temperature</title></head><body>{\"airtemperature\":%dC}</p></body></html>\r\n", uBit.thermometer.getTemperature());
		
		//ManagedString html = buffer;
		ManagedString data = headers + html;
		ManagedString cmd = "AT+CIPSEND=" + id + "," + ManagedString(data.length()) + "\r\n";
		uBit.serial.send(cmd, SYNC_SPINWAIT);
		
		s = "";
		int retry = 40;
		
		do {
			uBit.sleep(100);
			s = s + uBit.serial.read(500, ASYNC);
			retry--;
		} while (find(">", s) == 0 && retry != 0);
	
		uBit.serial.send(data, SYNC_SPINWAIT);
		if (waitForWiFi("OK", 100, 100) == 0) return 0;
			
		if (DEBUG)debug("\n\rData Sent\n\r");
			
		cmd = "AT+CIPCLOSE=" + id + "\r\n"; 
		uBit.serial.send(cmd, SYNC_SPINWAIT);
		if (waitForWiFi("OK", 100, 100) == 0) return 0;
	}
}

void debug(ManagedString s) {
	uBit.serial.redirect(USBTX, USBRX);
	uBit.serial.send(s, SYNC_SPINWAIT);
	uBit.serial.redirect(Tx, Rx);
}

int find(ManagedString c, ManagedString s) {
	int i; 
	for (i = 0; i < (s.length() - c.length()); i++) {
		if (c == s.substring(i, c.length())) break; 
	}
	if (i == (s.length() - c.length())) return 0;
	return i; 
}

int waitForWiFi(ManagedString target, int retry, int pause) {
	ManagedString s;
	do { 
		uBit.sleep(pause);
		if(s.length()>500)s="";
		s = s + uBit.serial.read(500, ASYNC); retry--;
	} while (find(target, s) == 0 && retry != 0);
	
	if (DEBUG)debug("\n\r" + s + "\n\r");
	return retry;
}

실행 - 콘솔 로그

실행결과 - 브러우저에서 확인

micro:bit - 온도 측정

OS/micro:bit 2018.02.23 21:02 Posted by 파란크리스마스

출처 : That IoT Thing: BBC micro:bit

#include "MicroBit.h" 

MicroBit uBit;

void temperatureUpdate(MicroBitEvent) {
	uBit.display.scroll( uBit.thermometer.getTemperature());
}

int main() { 
	uBit.init();
	uBit.display.scroll( uBit.thermometer.getTemperature());
	uBit.messageBus.listen(MICROBIT_ID_THERMOMETER, MICROBIT_THERMOMETER_EVT_UPDATE, temperatureUpdate);
}

micro:bit - Elecfreaks Joystick:bit

OS/micro:bit 2018.02.15 20:19 Posted by 파란크리스마스

출처 : Arduino Space Invaders Part 8 - Scoring
ELECFREAKS Joystick:bit for Micro:bit - ElecFreaks
https://makecode.microbit.org/_M9eHWe0aMc1D

micro:bit - Elecfreaks Joystick:bit

   

JavaScript 소스

C++ 소스

#include "MicroBit.h"

MicroBit uBit;

// P10 = P0_6 - joystick down
AnalogIn joystick_button(P0_1);
AnalogIn joystick_y(P0_2);
AnalogIn joystick_x(P0_3);


int main()
{
  // Initialise the micro:bit runtime.
  uBit.init();
  uBit.display.scroll("joystick");

  while(1) { 
  	if (joystick_button.read() < 0.256) {
 		uBit.display.scroll("1");
 	} else if (joystick_button.read() < 0.597) {
 		uBit.display.scroll("2");
 	} else if (joystick_button.read() < 0.725) {
 		uBit.display.scroll("3");
 	} else if (joystick_button.read() < 0.793) {
 		uBit.display.scroll("4");
 	} else if (joystick_button.read() < 0.836) {
 		uBit.display.scroll("5");
 	} else if (joystick_button.read() < 0.938) {
 		uBit.display.scroll("6");
	} else if (joystick_x.read() < 0.4) {
 		uBit.display.scroll("-X");
 	} else if (joystick_x.read() > 0.6) {
 		uBit.display.scroll("+X");
 	} else if (joystick_y.read() < 0.4) {
 		uBit.display.scroll("-Y");
 	} else if (joystick_y.read() > 0.6) {
 		uBit.display.scroll("+Y");
 	} else {
 		uBit.display.clear();
 	}
 	wait(1.0 );
  }
}

활용 - Space invaders (Using Joystick:bit)

pulse-combined.hex

micro:bit - BLE - RC Car -PWM 사용

OS/micro:bit 2018.02.03 00:27 Posted by 파란크리스마스

본 체험 제품은 element14 의 후원을 받아 아이씨뱅큐㈜ 에서 진행하는 무상 체험단 활동으로 작성한 것입니다.

출처 : Motor Driver Board for the BBC micro:bit - V2 | Kitronik
Blog Yamasho: Delphi 10.2.2:Bleで Microbitと通信する。
googlesamples/android-BluetoothLeGatt - GitHub
ButtonService - micro:bit runtime
microbit-samples/source/examples/bluetooth-services/main.cpp - GitHub
https://github.com/lancaster-university/microbit-dal/issues/337
Advanced - micro:bit runtime - GitHub Pages
Send/Receive Data Using BLE and MBED | BBC:Microbit - Instructables

micro:bit - BLE - RC Car -PWM 사용

main.cpp

MicroBitRCCAR.apk.zip

pulse-combined.hex

micro:bit 확장 보드중에 모터 드라이버(Motor Driver Board for the BBC micro:bit - V2 | Kitronik)를 이용해서 RC Car를 만들어 보았습니다. 통신방식은 micro:bit에 내장된 BLE를 이용했고, 클라이언트는 Delphi를 이용해서 만들어 보았습니다. 제가 사용한 모터 드라이버는 RWM를 사용해서 속도 제어도 가능했습니다.

 

 

소스 - main.cpp

#include "MicroBit.h" 
#include "MicroBitUARTService.h"

MicroBit uBit;
MicroBitUARTService *uart;

#define MOTER_LOW            0
#define MOTER_HIGH           0.2 // 스피드 - 0 ~ 1 | 최대속도 = 1

PwmOut moter_right_front(P0_18);	//12 - right
PwmOut moter_right_back(P0_20);		//8
PwmOut moter_left_front(P0_3);		//16 - left
PwmOut moter_left_back(P0_16);			//0

//모터A,B 정회전
void bothMotorStart()
{
  moter_right_front = MOTER_HIGH;
  moter_right_back = MOTER_LOW;
  moter_left_front = MOTER_HIGH;
  moter_left_back = MOTER_LOW;
}
 
//모터A,B 역회전
void bothMotorBack()
{
  moter_right_front = MOTER_LOW;
  moter_right_back = MOTER_HIGH;
  moter_left_front = MOTER_LOW;
  moter_left_back = MOTER_HIGH;
}
   
//모터A,B Stop
void stopAllMotor()
{
  moter_right_front = MOTER_LOW;
  moter_right_back = MOTER_LOW;
  moter_left_front = MOTER_LOW;
  moter_left_back = MOTER_LOW;
}
   
//모터A 역회전, 모터B 정회전
void turnLeft()
{
  moter_right_front = MOTER_LOW;
  moter_right_back = MOTER_HIGH;
  moter_left_front = MOTER_HIGH;
  moter_left_back = MOTER_LOW;
}
   
//모터A 정회전, 모터B 역회전
void turnRight()
{
  moter_right_front = MOTER_HIGH;
  moter_right_back = MOTER_LOW;
  moter_left_front = MOTER_LOW;
  moter_left_back = MOTER_HIGH;
}
   
//모터A 정회전, 모터B Stop
void motorA_Rotation()
{
  moter_right_front = MOTER_HIGH;
  moter_right_back = MOTER_LOW;
  moter_left_front = MOTER_LOW;
  moter_left_back = MOTER_LOW;
}
   
//모터A Stop, 모터B 정회전
void motorB_Rotation()
{
  moter_right_front = MOTER_LOW;
  moter_right_back = MOTER_LOW;
  moter_left_front = MOTER_HIGH;
  moter_left_back = MOTER_LOW;
}
   
//모터A 역회전, 모터B Stop
void motorA_Reverse()
{
  moter_right_front = MOTER_LOW;
  moter_right_back = MOTER_HIGH;
  moter_left_front = MOTER_LOW;
  moter_left_back = MOTER_LOW;
}
   
//모터A Stop, 모터B 역회전
void motorB_Reverse()
{
  moter_right_front = MOTER_LOW;
  moter_right_back = MOTER_LOW;
  moter_left_front = MOTER_LOW;
  moter_left_back = MOTER_HIGH;
}

// we use events abd the 'connected' variable to keep track of the status of the Bluetooth connection
void onConnected(MicroBitEvent)
{
    uBit.display.print("C");

    while(1) {
      char command = uart->getc();
      uBit.display.print(command);
      
      if (command == 'F') {
      	bothMotorStart();
      } else if (command == 'B') {
      	bothMotorBack();
      } else if (command == 'L') {
      	turnLeft();
      } else if (command == 'R') {
      	turnRight();
      } else if (command == 'S') {
      	stopAllMotor();
      }
    }
}
 
void onDisconnected(MicroBitEvent)
{
    uBit.display.print("D");
}

int main() { 
  uBit.init();
  uBit.display.scroll("MOTER");
  
  /*  
  while(1) {
    bothMotorStart();
    wait(1);
    stopAllMotor();
    wait(1);
    bothMotorBack();
    wait(1);
    stopAllMotor();
    wait(1);
  }
  */
	
  uBit.messageBus.listen(MICROBIT_ID_BLE, MICROBIT_BLE_EVT_CONNECTED, onConnected);
  uBit.messageBus.listen(MICROBIT_ID_BLE, MICROBIT_BLE_EVT_DISCONNECTED, onDisconnected);
	
  uart = new MicroBitUARTService(*uBit.ble, 32, 32); 
  uBit.display.scroll("UART ready");

  release_fiber();   
}

실행

마이크로비트 공식 구입처 : 아이씨뱅큐 http://www.icbanq.com/
엘리먼트14의 특장점 - 글로벌 전자부품 유통회사, 6만원 이상 무료배송, 60만가지 재고 보유, MOQ 없음, 한글 웹사이트, 국내서비스센터 운영 (http://kr.element14.com/?CMP=DSP-ODB-KR-JAN2018-BLOG-ICBanQ1-HOMEPAGE)

마이크로비트 공식 카페 : http://cafe.naver.com/bbcmicro
아이씨뱅큐 공식 블로그 : http://blog.naver.com/icbanq

micro:bit - Servo(SG-90) 모터 제어

OS/micro:bit 2018.01.28 19:10 Posted by 파란크리스마스

본 체험 제품은 element14 의 후원을 받아 아이씨뱅큐㈜ 에서 진행하는 무상 체험단 활동으로 작성한 것입니다.

출처 : lampbotics: mbed Servo Control - 0 to 180º fix - Thomas Murphy
BLENano_SimpleControls - SimpleControls works with the BLEController iOS/Android App. | Mbed
Servo - A class to control a model R/C servo, using a PwmOut | Mbed
Input/Output Pins — BBC micro:bit MicroPython 0.0.1 documentation
Visual Bastic.Net Serial 통신 - Create a basic BBC Micro:Bit Air Mouse – Hardware Hacks
micro:bit IoT In C - Pulse Width Modulation, Servos And More

micro:bit - Servo(SG-90) 모터 제어

micro:bit를 이용한 서보모터중에 가장 저렴한 SG-90을 제어하는 예제를 구현해보았습니다.

Servo.h

#ifndef _SERVO_H
#define _SERVO_H

#include "mbed.h"

class Servo
{
public:
    Servo(PinName pin);
    ~Servo(void);
    
    void write(unsigned char degree);

private:
    void convert(unsigned char degree);
    
    PwmOut _servo;
    unsigned int pulse;
};

#endif

Servo.cpp

#include "Servo.h"

Servo::Servo(PinName pin) : _servo(pin)
{
    _servo.period_ms(20);
}

Servo::~Servo(void)
{
    
}

void Servo::write(unsigned char degree)
{
    convert(degree);
    _servo.pulsewidth_us(pulse);
}

void Servo::convert(unsigned char degree)
{
    // 0~180 degree correspond to 500~2500
    pulse = degree * 11 + 500;
}

main.cpp

#include "MicroBit.h"
#include "Servo.h"

/*
PwmOut servo(P0_1);
int main() {
    servo.period(0.020);          
    while (1) {
        for(float offset=0.0003; offset<0.003; offset+=0.0001) {
            servo.pulsewidth(offset); 
            wait(0.25);
        }
    }
}
*/

#define SERVO_PIN P0_1

Serial pc(USBTX, USBRX);
Servo myservo(SERVO_PIN);

int main() 
{  
    int degree = 0;
    int direction = 1;
    
    while(1)
    {
        
        pc.printf("degree=%d \n\r",degree);
        myservo.write(degree);
            
        if(direction==1)
        {
            degree = degree + 5;
        }
            
        if (direction==2)
        {
            degree = degree - 5; 
        }
            
        if(degree>180)
        {
            degree = 180;
            direction = 2;
        }
        if(degree<0)
        {
            degree = 0;
            direction = 1;
        }
            
        wait(0.05);
    }
}

실행

setServoValue 함수를 사용하는 방법

출처 : micro:bit IoT In C - Pulse Width Modulation, Servos And More

#include "MicroBit.h"
MicroBit uBit;

int main() {
    uBit.init();
    for (;;) {
        uBit.io.P0.setServoValue(0);
        uBit.sleep(1000);
        uBit.io.P0.setServoValue(90);
        uBit.sleep(1000);
        uBit.io.P0.setServoValue(180);
        uBit.sleep(1000);
    }
    release_fiber();
    return 0;
}

아나로그 output을 이용하는 방법

출처 : micro:bit IoT In C - Pulse Width Modulation, Servos And More

#include "MicroBit.h"
MicroBit uBit;

int main() {
    uBit.init();
    uBit.io.P0.setAnalogValue(0);
    uBit.io.P0.setAnalogPeriod(20);

   for (;;) {
    uBit.io.P0.setAnalogValue(52 * 0 / 180 + 920);
    uBit.sleep(1000);
    uBit.io.P0.setAnalogValue(52 * 90 / 180 + 920);
    uBit.sleep(1000);
    uBit.io.P0.setAnalogValue(52 * 180 / 180 + 920);
    uBit.sleep(1000);
  }
  release_fiber();
  return 0;
}


마이크로비트 공식 구입처 : 아이씨뱅큐 http://www.icbanq.com/
엘리먼트14의 특장점 - 글로벌 전자부품 유통회사, 6만원 이상 무료배송, 60만가지 재고 보유, MOQ 없음, 한글 웹사이트, 국내서비스센터 운영 (http://kr.element14.com/?CMP=DSP-ODB-KR-JAN2018-BLOG-ICBanQ1-HOMEPAGE)

마이크로비트 공식 카페 : http://cafe.naver.com/bbcmicro
아이씨뱅큐 공식 블로그 : http://blog.naver.com/icbanq



 

티스토리 툴바