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);
}

Arduino Uno - ESP8266 ESP-01 Serial Wireless WIFI Module

OS/Arduino 2018.02.23 17:12 Posted by 파란크리스마스

출처 : GitHub - bportaluri/WiFiEsp: Arduino WiFi library for ESP8266 modules
GitHub - Diaoul/arduino-ESP8266: An Arduino library to manage the ESP8266.

WiFiEsp / ConnectWPA,ino

출처 : GitHub - bportaluri/WiFiEsp: Arduino WiFi library for ESP8266 modules

/*
 WiFiEsp example: ConnectWPA
 
 This example connects to an encrypted WiFi network using an ESP8266 module.
 Then it prints the  MAC address of the WiFi shield, the IP address obtained
 and other network details.

 For more details see: http://yaab-arduino.blogspot.com/p/wifiesp-example-connect.html
*/

#include "WiFiEsp.h"

// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(6, 7); // RX, TX
#endif

char ssid[] = "Twim";            // your network SSID (name)
char pass[] = "12345678";        // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status

void setup()
{
  // initialize serial for debugging
  Serial.begin(115200);
  // initialize serial for ESP module
  Serial1.begin(115200);
  // initialize ESP module
  WiFi.init(&Serial1);

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  Serial.println("You're connected to the network");
}

void loop()
{
  // print the network connection information every 10 seconds
  Serial.println();
  printCurrentNet();
  printWifiData();
  
  delay(10000);
}

void printWifiData()
{
  // print your WiFi shield's IP address
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print your MAC address
  byte mac[6];
  WiFi.macAddress(mac);
  char buf[20];
  sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X", mac[5], mac[4], mac[3], mac[2], mac[1], mac[0]);
  Serial.print("MAC address: ");
  Serial.println(buf);
}

void printCurrentNet()
{
  // print the SSID of the network you're attached to
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print the MAC address of the router you're attached to
  byte bssid[6];
  WiFi.BSSID(bssid);
  char buf[20];
  sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X", bssid[5], bssid[4], bssid[3], bssid[2], bssid[1], bssid[0]);
  Serial.print("BSSID: ");
  Serial.println(buf);

  // print the received signal strength
  long rssi = WiFi.RSSI();
  Serial.print("Signal strength (RSSI): ");
  Serial.println(rssi);
}

arduino-ESP8266 / Complete.ino

출처 : GitHub - Diaoul/arduino-ESP8266: An Arduino library to manage the ESP8266.

#include <SoftwareSerial.h>

#include "ESP8266.h"

SoftwareSerial esp8266Serial = SoftwareSerial(6, 7); // RX, TX
ESP8266 wifi = ESP8266(esp8266Serial);

void setup()
{
    Serial.begin(115200);

    // ESP8266
    esp8266Serial.begin(115200);
    wifi.begin();
    wifi.setTimeout(1000);

    /****************************************/
    /******       Basic commands       ******/
    /****************************************/
    // test
    /*Serial.print("test: ");
    Serial.println(getStatus(wifi.test()));*/

    // restart
    /*Serial.print("restart: ");
    Serial.println(getStatus(wifi.restart()));*/

    // getVersion
    char version[16] = {};
    Serial.print("getVersion: ");
    Serial.print(getStatus(wifi.getVersion(version, 16)));
    Serial.print(" : ");
    Serial.println(version);

    // deepSleep
    /*Serial.print("deepSleep: ");
    Serial.println(wifi.deepSleep(5000));*/

    // setBaudrate
    /*Serial.print("setBaudrate: ");
    Serial.println(wifi.setBaudrate(9600));*/

    /****************************************/
    /******        WiFi commands       ******/
    /****************************************/
    // setWifiMode
    Serial.print("setWifiMode: ");
    Serial.println(getStatus(wifi.setMode(ESP8266_WIFI_ACCESSPOINT)));

    // getWifiMode
    ESP8266WifiMode mode;
    Serial.print("getWifiMode: ");
    Serial.println(getStatus(wifi.getMode(&mode)));

    // joinAP
    /*Serial.print("joinAP: ");
    Serial.println(getStatus(wifi.joinAP("ssid", "password")));*/

    // getAP
    /*char ap[32] = {};
    Serial.print("getAP: ");
    Serial.print(getStatus(wifi.getAP(ap)));
    Serial.print(" : ");
    Serial.println(ap);*/

    // quitAP
    /*Serial.print("quitAP: ");
    Serial.println(getStatus(wifi.quitAP()));*/

    // setAPConfiguration
    Serial.print("setAPConfiguration: ");
    Serial.println(getStatus(wifi.setAPConfiguration("ESP8266", "awesomelib", 10, ESP8266_ENCRYPTION_WPA_WPA2_PSK)));
    wifi.restart();

    // getAPConfiguration
    char ssid[32] = {};
    char password[63] = {};
    uint8_t channel;
    ESP8266Encryption encryption;
    Serial.print("getAPConfiguration: ");
    Serial.print(getStatus(wifi.getAPConfiguration(ssid, password, channel, encryption)));
    Serial.print(" : ");
    Serial.print(ssid);
    Serial.print(" - ");
    Serial.print(password);
    Serial.print(" - ");
    Serial.print(channel);
    Serial.print(" - ");
    Serial.println(encryption);

    // setDHCP
    Serial.print("setDHCP STA: ");
    Serial.println(getStatus(wifi.setDHCP(ESP8266_WIFI_STATION, false)));
    Serial.print("setDHCP AP: ");
    Serial.println(getStatus(wifi.setDHCP(ESP8266_WIFI_ACCESSPOINT, true)));

    // setMAC
    /*byte mac[6] = {0x11, 0x11, 0x11, 0x11, 0x11, 0x11};
    Serial.print("setMAC AP: ");
    Serial.println(getStatus(wifi.setMAC(ESP8266_WIFI_ACCESSPOINT, mac)));*/

    // getMAC
    byte mac[6] = {};
    Serial.print("getMAC STA: ");
    Serial.print(getStatus(wifi.getMAC(ESP8266_WIFI_STATION, mac)));
    Serial.print(" : ");
    for (uint8_t i = 0; i < 6; i++) {
      Serial.print(mac[i], HEX);
      if (i < 5)
        Serial.print(":");
    }
    Serial.println();
    Serial.print("getMAC AP: ");
    Serial.print(getStatus(wifi.getMAC(ESP8266_WIFI_ACCESSPOINT, mac)));
    Serial.print(" : ");
    for (uint8_t i = 0; i < 6; i++) {
      Serial.print(mac[i], HEX);
      if (i < 5)
        Serial.print(":");
    }
    Serial.println();

    // setIP
    /*IPAddress ipAP = IPAddress(10, 0, 4, 1);
    Serial.print("setIP AP: ");
    Serial.print(getStatus(wifi.setIP(ESP8266_WIFI_ACCESSPOINT, ipAP)));
    Serial.print(" : ");
    Serial.println(ipAP);*/

    // getIP
    IPAddress ip;
    Serial.print("getIP STA: ");
    Serial.print(getStatus(wifi.getIP(ESP8266_WIFI_STATION, ip)));
    Serial.print(" : ");
    Serial.println(ip);
    Serial.print("getIP AP: ");
    Serial.print(getStatus(wifi.getIP(ESP8266_WIFI_ACCESSPOINT, ip)));
    Serial.print(" : ");
    Serial.println(ip);

    /****************************************/
    /******       TCP/IP commands      ******/
    /****************************************/
    // connect
    /*Serial.print("connect: ");
    Serial.println(getStatus(wifi.connect(ESP8266_PROTOCOL_TCP, IPAddress(192,168,4,100), 4000)));*/

    // send
    /*Serial.print("send: ");
    Serial.println(getStatus(wifi.send("Hello World\n")));*/

    // close
    /*Serial.print("close: ");
    Serial.println(getStatus(wifi.close()));*/

    // setMultipleConnections
    Serial.print("setMultipleConnections: ");
    Serial.println(getStatus(wifi.setMultipleConnections(true)));

    // getMultipleConnections
    /*bool multipleConnections;
    Serial.print("getMultipleConnections: ");
    Serial.print(getStatus(wifi.getMultipleConnections(multipleConnections)));
    Serial.print(" : ");
    Serial.println(multipleConnections);*/

    // createServer
    Serial.print("createServer: ");
    Serial.println(getStatus(wifi.createServer(4000)));

    // deleteServer
    Serial.print("deleteServer: ");
    Serial.println(getStatus(wifi.deleteServer()));

    // setServerTimeout
    /*Serial.print("setServerTimeout: ");
    Serial.println(getStatus(wifi.setServerTimeout(10)));*/

    // getServerTimeout
    /*unsigned int timeout;
    Serial.print("getServerTimeout: ");
    Serial.print(getStatus(wifi.getServerTimeout(timeout)));
    Serial.print(" : ");
    Serial.println(timeout);*/
}

void loop()
{
    /****************************************/
    /******        WiFi commands       ******/
    /****************************************/
    // getConnectedStations
    /*ESP8266Station stations[5];
    unsigned int stationCount;
    Serial.print("getConnectedStations: ");
    Serial.print(getStatus(wifi.getConnectedStations(stations, stationCount, 5)));
    Serial.print(" : ");
    Serial.println(stationCount);
    for (uint8_t i = 0; i < stationCount; i++) {
      Serial.print(" - ");
      Serial.print(stations[i].ip);
      Serial.print(" - ");
      for (uint8_t j = 0; j < 6; j++) {
        Serial.print(stations[i].mac[j], HEX);
        if (j < 5)
          Serial.print(":");
      }
      Serial.println();
    }
    delay(5000);*/

    /****************************************/
    /******       TCP/IP commands      ******/
    /****************************************/
    // getConnectionStatus
    /*ESP8266ConnectionStatus connectionStatus;
    ESP8266Connection connections[5];
    unsigned int connectionCount;
    Serial.print("getConnectionStatus: ");
    Serial.print(getStatus(wifi.getConnectionStatus(connectionStatus, connections, connectionCount)));
    Serial.print(" : ");
    Serial.println(connectionCount);
    for (int i = 0; i < connectionCount; i++) {
      Serial.print(" - Connection: ");
      Serial.print(connections[i].id);
      Serial.print(" - ");
      Serial.print(getProtocol(connections[i].protocol));
      Serial.print(" - ");
      Serial.print(connections[i].ip);
      Serial.print(":");
      Serial.print(connections[i].port);
      Serial.print(" - ");
      Serial.println(getRole(connections[i].role));
    }
    delay(5000);*/


    // read data
    /*unsigned int id;
    int length;
    int totalRead;
    char buffer[11] = {};

    if ((length = wifi.available()) > 0) {
      id = wifi.getId();
      totalRead = wifi.read(buffer, 10);

      if (length > 0) {
        Serial.print("Received ");
        Serial.print(totalRead);
        Serial.print("/");
        Serial.print(length);
        Serial.print(" bytes from client ");
        Serial.print(id);
        Serial.print(": ");
        Serial.println((char*)buffer);
      }
    }*/
}

String getStatus(bool status)
{
    if (status)
        return "OK";

    return "KO";
}

String getStatus(ESP8266CommandStatus status)
{
    switch (status) {
    case ESP8266_COMMAND_INVALID:
        return "INVALID";
        break;

    case ESP8266_COMMAND_TIMEOUT:
        return "TIMEOUT";
        break;

    case ESP8266_COMMAND_OK:
        return "OK";
        break;

    case ESP8266_COMMAND_NO_CHANGE:
        return "NO CHANGE";
        break;

    case ESP8266_COMMAND_ERROR:
        return "ERROR";
        break;

    case ESP8266_COMMAND_NO_LINK:
        return "NO LINK";
        break;

    case ESP8266_COMMAND_TOO_LONG:
        return "TOO LONG";
        break;

    case ESP8266_COMMAND_FAIL:
        return "FAIL";
        break;

    default:
        return "UNKNOWN COMMAND STATUS";
        break;
    }
}

String getRole(ESP8266Role role)
{
    switch (role) {
    case ESP8266_ROLE_CLIENT:
        return "CLIENT";
        break;

    case ESP8266_ROLE_SERVER:
        return "SERVER";
        break;

    default:
        return "UNKNOWN ROLE";
        break;
    }
}

String getProtocol(ESP8266Protocol protocol)
{
    switch (protocol) {
    case ESP8266_PROTOCOL_TCP:
        return "TCP";
        break;

    case ESP8266_PROTOCOL_UDP:
        return "UDP";
        break;

    default:
        return "UNKNOWN PROTOCOL";
        break;
    }
}

arduino-ESP8266 / HttpRequest.ino

출처 : GitHub - Diaoul/arduino-ESP8266: An Arduino library to manage the ESP8266.
Serial WiFi 모듈 (ESP8266) 활용편 | Hard Copy Arduino

#include <SoftwareSerial.h>

#include "ESP8266.h"

#define SSID "xxxxxxxx"
#define PASS "xxxxxxxx"
#define DST_IP "220.181.111.85" //baidu.com

SoftwareSerial esp8266Serial = SoftwareSerial(6, 7); // RX, TX
ESP8266 wifi = ESP8266(esp8266Serial);

void setup()
{
    Serial.begin(115200);

    // ESP8266
    esp8266Serial.begin(115200);
    wifi.begin();
    wifi.setTimeout(1000);

    /****************************************/
    /******       Basic commands       ******/
    /****************************************/
    // test
    Serial.print("test: ");
    Serial.println(getStatus(wifi.test()));

    // restart
    Serial.print("restart: ");
    Serial.println(getStatus(wifi.restart()));

    // getVersion
    char version[16] = {};
    Serial.print("getVersion: ");
    Serial.print(getStatus(wifi.getVersion(version, 16)));
    Serial.print(" : ");
    Serial.println(version);


    /****************************************/
    /******        WiFi commands       ******/
    /****************************************/
    // joinAP
    Serial.print("joinAP: ");
    Serial.println(getStatus(wifi.joinAP(SSID, PASS)));


    /****************************************/
    /******       TCP/IP commands      ******/
    /****************************************/
    // connect
    Serial.print("connect: ");
    Serial.println(getStatus(wifi.connect(ESP8266_PROTOCOL_TCP, DST_IP, 80)));

    // send
    Serial.print("send: ");
    Serial.println(getStatus(wifi.send("GET / HTTP/1.0\r\n\r\n")));

}

void loop()
{
    /****************************************/
    /******        WiFi commands       ******/
    /****************************************/

    // read data
    unsigned int id;
    int length;
    int totalRead;
    char buffer[300] = {};

    if ((length = wifi.available()) > 0) {
      id = wifi.getId();
      totalRead = wifi.read(buffer, 300);

      if (length > 0) {
        Serial.print("Received ");
        Serial.print(totalRead);
        Serial.print("/");
        Serial.print(length);
        Serial.print(" bytes from client ");
        //Serial.print("from client ");
        Serial.print(id);
        Serial.print(": ");
        Serial.println((char*)buffer);
      }
    }
}

String getStatus(bool status)
{
    if (status)
        return "OK";

    return "KO";
}

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