示例#1
0
/*JSON{
  "type" : "method",
  "class" : "SPI",
  "name" : "write",
  "generate" : "jswrap_spi_write",
  "params" : [
    ["data","JsVarArray",["One or more items to write. May be ints, strings, arrays, or objects of the form `{data: ..., count:#}`.","If the last argument is a pin, it is taken to be the NSS pin"]]
  ]
}
Write a character or array of characters to SPI - without reading the result back.

For maximum speeds, please pass either Strings or Typed Arrays as arguments.
*/
void jswrap_spi_write(JsVar *parent, JsVar *args) {
  NOT_USED(parent);
  IOEventFlags device = jsiGetDeviceFromClass(parent);

  spi_sender spiSend;
  spi_sender_data spiSendData;
  if (!jsspiGetSendFunction(parent, &spiSend, &spiSendData))
    return;


  Pin nss_pin = PIN_UNDEFINED;
  // If the last value is a pin, use it as the NSS pin
  JsVarInt len = jsvGetArrayLength(args);
  if (len>0) {    
    JsVar *last = jsvGetArrayItem(args, len-1); // look at the last value
    if (jsvIsPin(last)) {
      nss_pin = jshGetPinFromVar(last);    
      jsvUnLock(jsvArrayPop(args));
    }
    jsvUnLock(last);
  }

  // we're only sending (no receive)
  if (DEVICE_IS_SPI(device)) jshSPISetReceive(device, false);

  // assert NSS
  if (nss_pin!=PIN_UNDEFINED) jshPinOutput(nss_pin, false);
  // Write data
  jsvIterateCallback(args, (void (*)(int,  void *))spiSend, &spiSendData);
  // Wait until SPI send is finished, and flush data
  if (DEVICE_IS_SPI(device))
    jshSPIWait(device);
  // de-assert NSS
  if (nss_pin!=PIN_UNDEFINED) jshPinOutput(nss_pin, true);
}
示例#2
0
/*JSON{
  "type" : "function",
  "name" : "setSleepIndicator",
  "generate" : "jswrap_interface_setSleepIndicator",
  "params" : [
    ["pin","JsVar",""]
  ]
}
When Espruino is asleep, set the pin specified here low (when it's awake, set it high). Set this to undefined to disable the feature.

Please see http://www.espruino.com/Power+Consumption for more details on this.
 */
void jswrap_interface_setSleepIndicator(JsVar *pinVar) {
  Pin oldPin = pinSleepIndicator;
  pinSleepIndicator = jshGetPinFromVar(pinVar);
  // we should be awake right now anyway, so set stuff up right
  if (pinSleepIndicator!=oldPin) {
    if (oldPin!=PIN_UNDEFINED) jshPinOutput(oldPin, 0);
    if (pinSleepIndicator!=PIN_UNDEFINED) jshPinOutput(pinSleepIndicator, 1);
  }
}
示例#3
0
/*JSON{
  "type" : "function",
  "name" : "setBusyIndicator",
  "generate" : "jswrap_interface_setBusyIndicator",
  "params" : [
    ["pin","JsVar",""]
  ]
}
When Espruino is busy, set the pin specified here high. Set this to undefined to disable the feature.
*/
void jswrap_interface_setBusyIndicator(JsVar *pinVar) {
  Pin oldPin = pinBusyIndicator;
  pinBusyIndicator = jshGetPinFromVar(pinVar);
  // we should be busy right now anyway, so set stuff up right
  if (pinBusyIndicator!=oldPin) {
    if (oldPin!=NC) jshPinOutput(oldPin, 0);
    if (pinBusyIndicator!=NC) jshPinOutput(pinBusyIndicator, 1);
  }
}
示例#4
0
/*JSON{
  "type" : "method",
  "class" : "SPI",
  "name" : "send4bit",
  "generate" : "jswrap_spi_send4bit",
  "params" : [
    ["data","JsVar","The data to send - either an integer, array, or string"],
    ["bit0","int32","The 4 bits to send for a 0 (MSB first)"],
    ["bit1","int32","The 4 bits to send for a 1 (MSB first)"],
    ["nss_pin","pin","An nSS pin - this will be lowered before SPI output and raised afterwards (optional). There will be a small delay between when this is lowered and when sending starts, and also between sending finishing and it being raised."]
  ]
}
Send data down SPI, using 4 bits for each 'real' bit (MSB first). This can be useful for faking one-wire style protocols

Sending multiple bytes in one call to send is preferable as they can then be transmitted end to end. Using multiple calls to send() will result in significantly slower transmission speeds.
 */
void jswrap_spi_send4bit(JsVar *parent, JsVar *srcdata, int bit0, int bit1, Pin nss_pin) {
  NOT_USED(parent);
  IOEventFlags device = jsiGetDeviceFromClass(parent);
  if (!DEVICE_IS_SPI(device)) {
    jsExceptionHere(JSET_ERROR, "SPI.send4bit only works on hardware SPI");
    return;
  }

  jshSPISet16(device, true); // 16 bit output

  if (bit0==0 && bit1==0) {
    bit0 = 0x01;
    bit1 = 0x03;
  }
  bit0 = bit0 & 0x0F;
  bit1 = bit1 & 0x0F;

  if (!jshIsDeviceInitialised(device)) {
    JshSPIInfo inf;
    jshSPIInitInfo(&inf);
    jshSPISetup(device, &inf);
  }

  // we're just sending (no receive)
  jshSPISetReceive(device, false);
  // assert NSS
  if (nss_pin!=PIN_UNDEFINED) jshPinOutput(nss_pin, false);

  // send data
  if (jsvIsNumeric(srcdata)) {
    jsspiSend4bit(device, (unsigned char)jsvGetInteger(srcdata), bit0, bit1);
  } else if (jsvIsIterable(srcdata)) {
    jshInterruptOff();
    JsvIterator it;
    jsvIteratorNew(&it, srcdata);
    while (jsvIteratorHasElement(&it)) {
      unsigned char in = (unsigned char)jsvIteratorGetIntegerValue(&it);
      jsspiSend4bit(device, in, bit0, bit1);
      jsvIteratorNext(&it);
    }
    jsvIteratorFree(&it);
    jshInterruptOn();
  } else {
    jsExceptionHere(JSET_ERROR, "Variable type %t not suited to transmit operation", srcdata);
  }

  jshSPIWait(device); // wait until SPI send finished and clear the RX buffer

  // de-assert NSS
  if (nss_pin!=PIN_UNDEFINED) jshPinOutput(nss_pin, true);
  jshSPISet16(device, false); // back to 8 bit
}
示例#5
0
文件: main.c 项目: sequoiar/Espruino
void setLEDs(int l) {
  jshPinOutput(LED1_PININDEX, l&1);
  jshPinOutput(LED2_PININDEX, (l>>1)&1);
#ifdef LED3_PININDEX
  jshPinOutput(LED3_PININDEX, (l>>2)&1);
#endif
}
示例#6
0
/*JSON{
  "type"     : "method",
  "class"    : "Pin",
  "name"     : "write",
  "generate" : "jswrap_pin_write",
  "params"   : [
    ["value", "bool", "Whether to set output high (true/1) or low (false/0)"]
  ]
}
Sets the output state of the pin to the parameter given

 **Note:** if you didn't call `pinMode` beforehand then this function will also reset pin's state to `"output"`
 */
void jswrap_pin_write(
    JsVar *parent, //!< The class instance representing the Pin.
    bool value     //!< The value to set the pin.
  ) {
  Pin pin = jshGetPinFromVar(parent);
  jshPinOutput(pin, value);
}
示例#7
0
/*JSON{ "type":"function", "name" : "digitalWrite",
         "description" : ["Set the digital value of the given pin",
                          "If pin is an array of pins, eg. ```[A2,A1,A0]``` the value will be treated as an integer where the first array element is the MSB" ],
         "generate" : "jswrap_io_digitalWrite",
         "params" : [ [ "pin", "JsVar", "The pin to use"],
                      [ "value", "int", "Whether to pulse high (true) or low (false)"] ]
}*/
void jswrap_io_digitalWrite(JsVar *pinVar, JsVarInt value) {
  if (jsvIsArray(pinVar)) {
    JsVarRef pinName = pinVar->lastChild; // NOTE: start at end and work back!
    while (pinName) {
      JsVar *pinNamePtr = jsvLock(pinName);
      JsVar *pinPtr = jsvSkipName(pinNamePtr);
      jshPinOutput(jshGetPinFromVar(pinPtr), value&1);
      jsvUnLock(pinPtr);
      pinName = pinNamePtr->prevSibling;
      jsvUnLock(pinNamePtr);
      value = value>>1; // next bit down
    }
  } else {
示例#8
0
void  SpiInit(void)
{
  // SPI config
  JshSPIInfo inf;
  jshSPIInitInfo(&inf);
  inf.pinSCK =  WLAN_CLK_PIN;
  inf.pinMISO = WLAN_MISO_PIN;
  inf.pinMOSI = WLAN_MOSI_PIN;
  inf.baudRate = 100000; // FIXME - just slow for debug
  inf.spiMode = SPIF_SPI_MODE_1;  // Mode 1   CPOL= 0  CPHA= 1
  jshSPISetup(WLAN_SPI, &inf);

  // WLAN CS, EN and WALN IRQ Configuration
  jshSetPinStateIsManual(WLAN_CS_PIN, false);
  jshPinOutput(WLAN_CS_PIN, 1); // de-assert CS
  jshSetPinStateIsManual(WLAN_EN_PIN, false);
  jshPinOutput(WLAN_EN_PIN, 0); // disable WLAN
  jshSetPinStateIsManual(WLAN_IRQ_PIN, true);
  jshPinSetState(WLAN_IRQ_PIN, JSHPINSTATE_GPIO_IN_PULLUP); // flip into read mode with pullup

  // wait a little (ensure that WLAN takes effect)
  jshDelayMicroseconds(500*1000); // force a 500ms delay! FIXME
}
示例#9
0
void lcdIdle_PCD8544(JsGraphics *gfx) {
  if (changeX1>=changeX2 && changeY1>=changeY2) {
    // write...
    int cy1 = changeY1 >> 3;
    int cy2 = changeY2 >> 3;
    int x,y;
    jshPinOutput(CE, 0);
    for (y=cy1;y<=cy2;y++) {
      jshPinOutput(DC, 0); // command
      jshSPISend(dev, 0x40 | y); // Y addr
      jshSPISend(dev, 0x80); // X addr
      jshPinOutput(DC, 1); // data
      for (x=changeX1;x<=changeX2;x++) 
        jshSPISend(dev, pixels[x+y*LCD_WIDTH]);
    }      
    jshPinOutput(DC, 0); // command
    jshSPISend(dev, 0x40); // reset?
    jshPinOutput(CE, 1);

    changeX1 = LCD_WIDTH;
    changeY1 = LCD_HEIGHT;
    changeX2 = 0;
    changeY2 = 0;
  }
示例#10
0
/*JSON{ "type":"staticmethod", 
         "class" : "WIZnet", "name" : "connect",
         "generate" : "jswrap_wiznet_connect",
         "description" : "Initialise the WIZnet module and return an Ethernet object",
         "params" : [ ],
         "return" : ["JsVar", "An Ethernet Object"], "return_object":"Ethernet"
}*/
JsVar *jswrap_wiznet_connect() {
  JsVar *ethObj = jspNewObject(0, "Ethernet");

  // SPI config
  JshSPIInfo inf;
  jshSPIInitInfo(&inf);
  inf.pinSCK =  ETH_CLK_PIN;
  inf.pinMISO = ETH_MISO_PIN;
  inf.pinMOSI = ETH_MOSI_PIN;
  inf.baudRate = 1000000;
  inf.spiMode = SPIF_SPI_MODE_0;
  jshSPISetup(ETH_SPI, &inf);

  // CS Configuration
  jshSetPinStateIsManual(ETH_CS_PIN, false);
  jshPinOutput(ETH_CS_PIN, 1); // de-assert CS

  // Wiznet
  reg_wizchip_cs_cbfunc(wizchip_select, wizchip_deselect);
  reg_wizchip_spi_cbfunc(wizchip_read, wizchip_write);

  /* wizchip initialize*/
  uint8_t tmp;
  uint8_t memsize[2][8] = { {2,2,2,2,2,2,2,2},{2,2,2,2,2,2,2,2}};

  if(ctlwizchip(CW_INIT_WIZCHIP,(void*)memsize) == -1)
  {
    jsiConsolePrint("WIZCHIP Initialized fail.\r\n");
    return 0;
  }

  /* PHY link status check */
  do {
    if(ctlwizchip(CW_GET_PHYLINK, (void*)&tmp) == -1) {
      jsiConsolePrint("Unknown PHY Link status.\r\n");
      return 0;
    }
  } while (tmp == PHY_LINK_OFF);

  JsNetwork net;
  networkCreate(&net, JSNETWORKTYPE_W5500);
  networkFree(&net);

  networkState = NETWORKSTATE_ONLINE;

  return ethObj;
}
示例#11
0
文件: jswrap_io.c 项目: etx/Espruino
/*JSON{
  "type"     : "function",
  "name"     : "digitalWrite",
  "generate" : "jswrap_io_digitalWrite",
  "params"   : [
    ["pin",   "JsVar","The pin to use"],
    ["value", "int","Whether to pulse high (true) or low (false)"]
  ]
}
Set the digital value of the given pin.

 **Note:** if you didn't call `pinMode` beforehand then this function will also reset pin's state to `"output"`

If pin argument is an array of pins (eg. `[A2,A1,A0]`) the value argument will be treated
as an array of bits where the last array element is the least significant bit.

In this case, pin values are set least significant bit first (from the right-hand side
of the array of pins). This means you can use the same pin multiple times, for
example `digitalWrite([A1,A1,A0,A0],0b0101)` would pulse A0 followed by A1.

If the pin argument is an object with a `write` method, the `write` method will
be called with the value passed through.
*/
void jswrap_io_digitalWrite(
    JsVar *pinVar, //!< A pin or pins.
    JsVarInt value //!< The value of the output.
  ) {
  // Handle the case where it is an array of pins.
  if (jsvIsArray(pinVar)) {
    JsVarRef pinName = jsvGetLastChild(pinVar); // NOTE: start at end and work back!
    while (pinName) {
      JsVar *pinNamePtr = jsvLock(pinName);
      JsVar *pinPtr = jsvSkipName(pinNamePtr);
      jshPinOutput(jshGetPinFromVar(pinPtr), value&1);
      jsvUnLock(pinPtr);
      pinName = jsvGetPrevSibling(pinNamePtr);
      jsvUnLock(pinNamePtr);
      value = value>>1; // next bit down
    }
  } else if (jsvIsObject(pinVar)) {
示例#12
0
void jshPinPulse(Pin pin, bool pulsePolarity, JsVarFloat pulseTime) {
  // ---- USE TIMER FOR PULSE
  if (!jshIsPinValid(pin)) {
       jsExceptionHere(JSET_ERROR, "Invalid pin!");
       return;
  }
  if (pulseTime<=0) {
    // just wait for everything to complete
    jstUtilTimerWaitEmpty();
    return;
  } else {
    // find out if we already had a timer scheduled
    UtilTimerTask task;
    if (!jstGetLastPinTimerTask(pin, &task)) {
      // no timer - just start the pulse now!
      jshPinOutput(pin, pulsePolarity);
      task.time = jshGetSystemTime();
    }
    // Now set the end of the pulse to happen on a timer
    jstPinOutputAtTime(task.time + jshGetTimeFromMilliseconds(pulseTime), &pin, 1, !pulsePolarity);
  }
}
示例#13
0
void blink(const char * pin, int msec){
  jshPinOutput(jshGetPinFromString(pin), 1);
  delay(msec/2);
  jshPinOutput(jshGetPinFromString(pin), 0);
  delay(msec/2);
} 
示例#14
0
文件: main.c 项目: Hmaal/Espruino
int main(void) {
  initHardware();
  int flashy = 0;
  BootloaderState state = BLS_UNDEFINED;
  char currentCommand = 0;

  while (1) {
    if (!jshIsUSBSERIALConnected()) {
      jshPinOutput(LED2_PININDEX, 0);
      // reset, led off
    } else {
      int f = (flashy>>9) & 0x7F;
      if (f&0x40) f=128-f;
      jshPinOutput(LED3_PININDEX, ((flashy++)&0xFF)<f);
      // flash led
      int d = getc();
      if (d>=0) { // if we have data
        if (state==BLS_EXPECT_DATA) {

        } else if (state==BLS_INITED) {
          currentCommand = d;
          state = BLS_COMMAND_FIRST_BYTE;
        } else if (state==BLS_COMMAND_FIRST_BYTE) {
          if (currentCommand == d^0xFF) {
            unsigned int addr,i;
            char chksum, buffer[256];
            unsigned int nBytesMinusOne, nPages;
            // confirmed
            switch (currentCommand) {
            case CMD_GET: // get bootloader info
              putc(ACK);
              putc(5); // 6 bytes
              // now report what we support
              putc(BOOTLOADER_MAJOR_VERSION<<4 | BOOTLOADER_MINOR_VERSION); // Bootloader version
              // list supported commands
              putc(CMD_GET);
              putc(CMD_GET_ID);
              putc(CMD_READ);
              putc(CMD_WRITE);
              putc(CMD_EXTERASE); // erase
              putc(ACK); // last byte
              break;
            case CMD_GET_ID: // get chip ID
              putc(ACK);
              putc(1); // 2 bytes
              // now report what we support
              putc(0x04);
              // 0x30 F1 XL density
              // 0x14 F1 high density
              putc(0x30); // TODO: really?
              putc(ACK); // last byte
              break;
            case CMD_READ: // read memory
              putc(ACK);
              addr = getc_blocking() << 24;
              addr |= getc_blocking()  << 16;
              addr |= getc_blocking()  << 8;
              addr |= getc_blocking();
              chksum = getc_blocking();
              // TODO: check checksum
              putc(ACK);
              setLEDs(2); // green = wait for data
              nBytesMinusOne = getc_blocking();
              chksum = getc_blocking();
              // TODO: check checksum
              putc(ACK);
              for (i=0;i<=nBytesMinusOne;i++)
                putc(((unsigned char*)addr)[i]);
              setLEDs(0); // off
              break;
            case CMD_WRITE: // write memory
              putc(ACK);
              addr = getc_blocking() << 24;
              addr |= getc_blocking()  << 16;
              addr |= getc_blocking()  << 8;
              addr |= getc_blocking();
              chksum = getc_blocking();
              // TODO: check checksum and address&3==0
              putc(ACK);
              setLEDs(2); // green = wait for data
              nBytesMinusOne = getc_blocking();
              for (i=0;i<=nBytesMinusOne;i++)
                buffer[i] = getc_blocking();
              chksum = getc_blocking();
              setLEDs(1); // red = write
              // TODO: check checksum and (nBytesMinusOne+1)&3==0
              FLASH_UnlockBank1();
              for (i=0;i<=nBytesMinusOne;i+=4) {
                unsigned int realaddr = addr+i;
                if (realaddr >= (FLASH_START+BOOTLOADER_SIZE)) // protect bootloader
                  FLASH_ProgramWord(realaddr, *(unsigned int*)&buffer[i]);
              }
              FLASH_LockBank1();
              setLEDs(0); // off
              putc(ACK); //  TODO - could speed up writes by ACKing beforehand if we have space
              break;
            case CMD_EXTERASE: // erase memory
              putc(ACK);
              nPages = getc_blocking() << 8;
              nPages |= getc_blocking();
              chksum = getc_blocking();
              // TODO: check checksum
              if (nPages == 0xFFFF) {
                // all pages (except us!)
                setLEDs(1); // red =  write
                FLASH_UnlockBank1();
                for (i=BOOTLOADER_SIZE;i<FLASH_TOTAL;i+=FLASH_PAGE_SIZE)
                  FLASH_ErasePage((uint32_t)(FLASH_START + i));
                FLASH_LockBank1();
                setLEDs(0); // off
                putc(ACK);
              } else {
                putc(NACK); // not implemented
              }
              break;
            default: // unknown command
              putc(NACK);
              break;
            }
          } else {
            // not correct
            putc(NACK);
          }
          state = BLS_INITED;
        } else {
          switch (d) {
          case 0x7F: // initialisation byte
                     putc(state == BLS_UNDEFINED ? ACK : NACK);
                     state = BLS_INITED;
                     break;
          }
        }
      }
    }
  }
}
示例#15
0
文件: main.c 项目: Hmaal/Espruino
void setLEDs(int l) {
  jshPinOutput(LED1_PININDEX, l&1);
  jshPinOutput(LED2_PININDEX, (l>>1)&1);
  jshPinOutput(LED3_PININDEX, (l>>2)&1);
}
示例#16
0
/*JSON{
  "type" : "staticmethod",
  "class" : "WIZnet",
  "name" : "connect",
  "generate" : "jswrap_wiznet_connect",
  "params" : [
    ["spi", "JsVar", "Device to use for SPI (or undefined to use the default)"],
    ["cs", "pin", "The pin to use for Chip Select"]
  ],
  "return" : ["JsVar","An Ethernet Object"],
  "return_object" : "Ethernet"
}
Initialise the WIZnet module and return an Ethernet object
*/
JsVar *jswrap_wiznet_connect(JsVar *spi, Pin cs) {

  IOEventFlags spiDevice;
  if (spi) {
    spiDevice = jsiGetDeviceFromClass(spi);
    if (!DEVICE_IS_SPI(spiDevice)) {
      jsExceptionHere(JSET_ERROR, "Expecting SPI device, got %q", spi);
      return 0;
    }
  } else {
    // SPI config
    JshSPIInfo inf;
    jshSPIInitInfo(&inf);
    inf.pinSCK =  ETH_CLK_PIN;
    inf.pinMISO = ETH_MISO_PIN;
    inf.pinMOSI = ETH_MOSI_PIN;
    inf.baudRate = 1000000;
    inf.spiMode = SPIF_SPI_MODE_0;
    jshSPISetup(ETH_SPI, &inf);
    spiDevice = ETH_SPI;
  }
  if (!jshIsPinValid(cs))
    cs = ETH_CS_PIN;

  JsNetwork net;
  networkCreate(&net, JSNETWORKTYPE_W5500);
  net.data.device = spiDevice;
  net.data.pinCS = cs;
  networkSet(&net);

  JsVar *ethObj = jspNewObject(0, "Ethernet");

  // CS Configuration
  jshSetPinStateIsManual(net.data.pinCS, false);
  jshPinOutput(net.data.pinCS, 1); // de-assert CS

  // Initialise WIZnet functions
  reg_wizchip_cs_cbfunc(wizchip_select, wizchip_deselect);
  reg_wizchip_spi_cbfunc(wizchip_read, wizchip_write);

  /* wizchip initialize*/
  uint8_t tmp;
  uint8_t memsize[2][8] = { {2,2,2,2,2,2,2,2}, {2,2,2,2,2,2,2,2}};

  if(ctlwizchip(CW_INIT_WIZCHIP,(void*)memsize) == -1)
  {
    jsiConsolePrint("WIZnet Initialize failed.\r\n");
    networkFree(&net);
    return 0;
  }

#if _WIZCHIP_ == 5500
  /* PHY link status check - W5100 doesn't have this */
  do {
    if(ctlwizchip(CW_GET_PHYLINK, (void*)&tmp) == -1) {
      jsiConsolePrint("Unknown PHY Link status.\r\n");
      networkFree(&net);
      return 0;
    }
  } while (tmp == PHY_LINK_OFF);
#endif

  networkFree(&net);

  networkState = NETWORKSTATE_ONLINE;

  return ethObj;
}
示例#17
0
void enableDASH(){
  WDEBUGLN("enabling DASH");
  jshPinOutput(jshGetPinFromString(PIN_DASH7_XTAL_EN), 1);
  jshPinOutput(jshGetPinFromString(PIN_DASH7_RST), 1);
  delay(80); //TODO: figure out why dash7 needs 80ms startup
}
示例#18
0
void cc3000_write_en_pin( unsigned char val )
{
  jshPinOutput(WLAN_EN_PIN, val == WLAN_ENABLE);
示例#19
0
/**
 * Send data through SPI.
 * The data can be in a variety of formats including:
 * * `numeric` - A single byte is transmitted.
 * * `string` - Each character in the string is transmitted.
 * * `iterable` - An iterable object is transmitted.
 * \return the Received bytes (MISO).  This is byte array.
 */
JsVar *jswrap_spi_send(
    JsVar *parent,  //!< A description of the SPI device to send data through.
    JsVar *srcdata, //!< The data to send through SPI.
    Pin    nss_pin  //!< The pin to toggle low then high (CS)
  ) {
  // Debug
  // jsiConsolePrintf("jswrap_spi_send called: parent=%j, srcdata=%j, nss_pin=%p\n", parent, srcdata, nss_pin);
  NOT_USED(parent);
  IOEventFlags device = jsiGetDeviceFromClass(parent);

  jswrap_spi_send_data data;
  if (!jsspiGetSendFunction(parent, &data.spiSend, &data.spiSendData))
    return 0;

  JsVar *dst = 0;

  // we're sending and receiving
  if (DEVICE_IS_SPI(device)) jshSPISetReceive(device, true);

  // assert NSS
  if (nss_pin!=PIN_UNDEFINED) jshPinOutput(nss_pin, false);

  // Now that we are setup, we can send the data.

  // Handle the data being a single byte value
  if (jsvIsNumeric(srcdata)) {
    int r = data.spiSend((unsigned char)jsvGetInteger(srcdata), &data.spiSendData);
    if (r<0) r = data.spiSend(-1, &data.spiSendData);
    dst = jsvNewFromInteger(r); // retrieve the byte (no send!)
  }
  // Handle the data being a string
  else if (jsvIsString(srcdata)) {
    dst = jsvNewFromEmptyString();
    JsvStringIterator it;
    jsvStringIteratorNew(&it, srcdata, 0);
    int incount = 0, outcount = 0;
    while (jsvStringIteratorHasChar(&it) && !jspIsInterrupted()) {
      unsigned char in = (unsigned char)jsvStringIteratorGetChar(&it);
      incount++;
      int out = data.spiSend(in, &data.spiSendData);
      if (out>=0) {
        outcount++;
        char outc = (char)out;
        jsvAppendStringBuf(dst, (char*)&outc, 1);
      }
      jsvStringIteratorNext(&it);
    }
    jsvStringIteratorFree(&it);
    // finally add the remaining bytes  (no send!)
    while (outcount < incount && !jspIsInterrupted()) {
      outcount++;
      unsigned char out = (unsigned char)data.spiSend(-1, &data.spiSendData);
      jsvAppendStringBuf(dst, (char*)&out, 1);
    }
  }
  // Handle the data being an iterable.
  else {
    int nBytes = jsvIterateCallbackCount(srcdata);
    dst = jsvNewTypedArray(ARRAYBUFFERVIEW_UINT8, nBytes);
    if (dst) {
      data.rxAmt = data.txAmt = 0;
      jsvArrayBufferIteratorNew(&data.it, dst, 0);
      // Write data
      jsvIterateCallback(srcdata, (void (*)(int,  void *))jswrap_spi_send_cb, &data);
      // Wait until SPI send is finished, and flush data
      while (data.rxAmt < data.txAmt && !jspIsInterrupted())
        jswrap_spi_send_cb(-1, &data);
      jsvArrayBufferIteratorFree(&data.it);
    }
  }

  // de-assert NSS
  if (nss_pin!=PIN_UNDEFINED) jshPinOutput(nss_pin, true);
  return dst;
}
示例#20
0
void  wizchip_deselect(void) {
  assert(networkGetCurrent());
  jshPinOutput(networkGetCurrent()->data.pinCS, 1); // active low
}
示例#21
0
/*JSON{ "type":"method", "class": "Pin", "name" : "write",
         "description" : "Sets the output state of the pin to the parameter given",
         "generate" : "jswrap_pin_write",
         "params" : [ [ "value", "bool", "Whether to set output high (true/1) or low (false/0)"] ]
}*/
void jswrap_pin_write(JsVar *parent, bool value) {
  Pin pin = jshGetPinFromVar(parent);
  jshPinOutput(pin, value);
}
示例#22
0
JsVar *jswrap_spi_send(JsVar *parent, JsVar *srcdata, Pin nss_pin) {
  NOT_USED(parent);
  IOEventFlags device = jsiGetDeviceFromClass(parent);

  jswrap_spi_send_data data;
  if (!jsspiGetSendFunction(parent, &data.spiSend, &data.spiSendData))
    return 0;

  JsVar *dst = 0;

  // we're sending and receiving
  if (DEVICE_IS_SPI(device)) jshSPISetReceive(device, true);

  // assert NSS
  if (nss_pin!=PIN_UNDEFINED) jshPinOutput(nss_pin, false);

  // send data
  if (jsvIsNumeric(srcdata)) {
    int r = data.spiSend((unsigned char)jsvGetInteger(srcdata), &data.spiSendData);
    if (r<0) r = data.spiSend(-1, &data.spiSendData);
    dst = jsvNewFromInteger(r); // retrieve the byte (no send!)
  } else if (jsvIsString(srcdata)) {
    dst = jsvNewFromEmptyString();
    JsvStringIterator it;
    jsvStringIteratorNew(&it, srcdata, 0);
    int incount = 0, outcount = 0;
    while (jsvStringIteratorHasChar(&it) && !jspIsInterrupted()) {
      unsigned char in = (unsigned char)jsvStringIteratorGetChar(&it);
      incount++;
      int out = data.spiSend(in, &data.spiSendData);
      if (out>=0) {
        outcount++;
        char outc = (char)out;
        jsvAppendStringBuf(dst, (char*)&outc, 1);
      }
      jsvStringIteratorNext(&it);
    }
    jsvStringIteratorFree(&it);
    // finally add the remaining bytes  (no send!)
    while (outcount < incount && !jspIsInterrupted()) {
      outcount++;
      unsigned char out = (unsigned char)data.spiSend(-1, &data.spiSendData);
      jsvAppendStringBuf(dst, (char*)&out, 1);
    }
  } else {
    int nBytes = jsvIterateCallbackCount(srcdata);
    dst = jsvNewTypedArray(ARRAYBUFFERVIEW_UINT8, nBytes);
    if (dst) {
      data.rxAmt = data.txAmt = 0;
      jsvArrayBufferIteratorNew(&data.it, dst, 0);
      // Write data
      jsvIterateCallback(srcdata, (void (*)(int,  void *))jswrap_spi_send_cb, &data);
      // Wait until SPI send is finished, and flush data
      while (data.rxAmt < data.txAmt && !jspIsInterrupted())
        jswrap_spi_send_cb(-1, &data);
      jsvArrayBufferIteratorFree(&data.it);
    }
  }

  // de-assert NSS
  if (nss_pin!=PIN_UNDEFINED) jshPinOutput(nss_pin, true);
  return dst;
}
示例#23
0
/**
  * @brief  This function turns the connection LED ON/OFF
  * @param  None
  * @retval None
  */
void SmartConfigLedOn(uint32_t ulTrueFalse)
{
  jshPinOutput(LED1_PININDEX, ulTrueFalse);
}
示例#24
0
/**
  * @brief  This function returns enables or disables CC3000 .
  * @param  None
  * @retval None
  */
void WriteWlanPin( unsigned char val )
{
  jshPinOutput(WLAN_EN_PIN, val == WLAN_ENABLE);
}
示例#25
0
void disableDASH(){
  /// TODO REINSTATE
  jshPinOutput(jshGetPinFromString(PIN_DASH7_XTAL_EN), 0);
  jshPinOutput(jshGetPinFromString(PIN_DASH7_RST), 0);
}
示例#26
0
void disableWifi() {
  jshPinOutput(jshGetPinFromString(PIN_ESP_RST), 0);
  jshPinOutput(jshGetPinFromString(PIN_ESP_CP), 0);
}
示例#27
0
/*JSON{ "type":"method", "class": "Pin", "name" : "reset",
         "description" : "Sets the output state of the pin to a 0",
         "generate" : "jswrap_pin_reset"
}*/
void jswrap_pin_reset(JsVar *parent) {
  Pin pin = jshGetPinFromVar(parent);
  jshPinOutput(pin, 0);
}
示例#28
0
void HAL_PCD_MspInit(PCD_HandleTypeDef* hpcd)
{
#ifdef STM32F4
  if(hpcd->Instance==USB_OTG_FS)
  {
    /* Peripheral clock enable */
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);
    RCC_AHB2PeriphClockCmd(RCC_AHB2Periph_OTG_FS, ENABLE) ; // __USB_OTG_FS_CLK_ENABLE();

  
    /**USB_OTG_FS GPIO Configuration    
    PA9     ------> USB_OTG_FS_VBUS
    PA11     ------> USB_OTG_FS_DM
    PA12     ------> USB_OTG_FS_DP 
    */

    /* Configure DM DP Pins */
    GPIO_InitTypeDef GPIO_InitStructure;
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11 |
                                  GPIO_Pin_12;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL ;
    GPIO_Init(GPIOA, &GPIO_InitStructure);

    GPIO_PinAFConfig(GPIOA,GPIO_PinSource11,GPIO_AF_OTG1_FS) ;
    GPIO_PinAFConfig(GPIOA,GPIO_PinSource12,GPIO_AF_OTG1_FS) ;

    /* Configure  VBUS Pin */
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
    GPIO_InitStructure.GPIO_OType = GPIO_OType_OD;
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL ;
    GPIO_Init(GPIOA, &GPIO_InitStructure);


    NVIC_InitTypeDef NVIC_InitStructure;
    NVIC_InitStructure.NVIC_IRQChannel = OTG_FS_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 12; // set this quite low. it can take a while to fill RX/TX buffers and don't let it break other stuff
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);
  }
#endif
#ifdef STM32F1
  RCC_USBCLKConfig(RCC_USBCLKSource_PLLCLK_1Div5);
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_USB, ENABLE);

  NVIC_InitTypeDef NVIC_InitStructure;
  /* Enable the USB interrupt */
  NVIC_InitStructure.NVIC_IRQChannel = USB_LP_CAN1_RX0_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 12; // set this quite low. it can take a while to fill RX/TX buffers and don't let it break other stuff
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);

  /* Enable the USB Wake-up interrupt */
  NVIC_InitStructure.NVIC_IRQChannel = USBWakeUp_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
  NVIC_Init(&NVIC_InitStructure);

  jshPinOutput(USB_DISCONNECT_PIN, 0); // turn on USB
#endif

}
示例#29
0
void  wizchip_deselect(void)
{
  jshPinOutput(ETH_CS_PIN, 1); // active low
}
示例#30
0
/*JSON{
  "type" : "init",
  "generate" : "jswrap_wice_init"
}*/
void jswrap_wice_init() {
  jspCallNamedFunction(execInfo.root, "USB.setConsole", 0, 0);
  jspEvaluate("USB.setConsole();");
#ifdef WICE_DEBUG
  WDEBUGLN("USB is console");
#endif
  /*JsVar *mode = jsvNewFromString("output");
  jswrap_io_pinMode(jshGetPinFromString(PIN_DASH7_XTAL_EN), mode);
  jswrap_io_pinMode(jshGetPinFromString(PIN_DASH7_RST), mode);
  jsvUnLock(mode);*/

  enableDASH();

  // Set up the DASH7 USART how we want it
  JshUSARTInfo inf;
  jshUSARTInitInfo(&inf);
  inf.baudRate = 115200;
  inf.pinRX = jshGetPinFromString(PIN_DASH7_RX);
  inf.pinTX = jshGetPinFromString(PIN_DASH7_TX);
  jshUSARTSetup(EV_SERIAL1, &inf);

  JsVar *serial = jspGetNamedField(execInfo.root, SERIAL1_DASH7, false);
  jswrap_object_addEventListener(serial, "data", dash7Callback, JSWAT_VOID | (JSWAT_JSVAR<<(JSWAT_BITS)));
  jsvUnLock(serial);

  startTime = jshGetSystemTime();

  wice_msg_init(&wifiMessage, wifiMessageBuffer, 2048);
  wice_msg_init(&dash7Message, dash7MessageBuffer, 256);


  options = jspEvaluate("x = {\"repeat\": \"true\", \"edge\": \"rising\", \"debounce\":\"50\"}");
  Pin btn = jshGetPinFromString("B10");
  JsVar *btnmode = jsvNewFromString("input");
  jswrap_io_pinMode(btn, btnmode);
  jsvUnLock(btnmode);

#ifdef GATEWAY
  WDEBUGLN("GATEWAY");
  blink(PIN_GRN, 50);
  /// opendrain and digitalwrite 1 will 'opencircuit it'
  /// http://www.espruino.com/Reference#l__global_pinMode
  JsVar *opendrain = jsvNewFromString("opendrain");
  WDEBUGSTRVAR(opendrain);
  jswrap_io_pinMode(jshGetPinFromString(PIN_ESP_GPIO_0), opendrain);
  jswrap_io_pinMode(jshGetPinFromString(PIN_ESP_GPIO_2), opendrain);
  jshPinOutput(jshGetPinFromString(PIN_ESP_GPIO_0), 1);
  jshPinOutput(jshGetPinFromString(PIN_ESP_GPIO_2), 1);
  jsvUnLock(opendrain);
  /// must opendrain gpio0/2 because of boot modes
  /// https://github.com/esp8266/esp8266-wiki/wiki/Boot-Process
  enableWifi();

  // Set up the Wifi USART how we want it
  JshUSARTInfo inf4;
  jshUSARTInitInfo(&inf4);
  inf4.baudRate = 115200;
  inf4.pinRX = jshGetPinFromString(PIN_ESP_RX);
  inf4.pinTX = jshGetPinFromString(PIN_ESP_TX);
  jshUSARTSetup(EV_SERIAL4, &inf4);

  /// make button restart wifi for gateway
  JsVar *restartWifi_fn = jsvNewNativeFunction(restartWifi, JSWAT_VOID);
  btnEvent = jswrap_interface_setWatch(restartWifi_fn,
                            btn, 
                            options);
  jsvUnLock(restartWifi_fn);
  /// configure wifi usart callback
  JsVar *wifiSerial = jspGetNamedField(execInfo.root, SERIAL4_WIFI, false);
  jswrap_object_addEventListener(wifiSerial, "data", wifiCallback, JSWAT_VOID | (JSWAT_JSVAR<<(JSWAT_BITS)));
  jsvUnLock(wifiSerial);
  doSendSerial();
#else 
  WDEBUGLN("NODE");
  blink(PIN_BLUE, 50);
  /// make button a forced measurement for nodes
  JsVar *doMeasurementAndWaitForResponse_fn = jsvNewNativeFunction(doMeasurementAndWaitForResponse, JSWAT_VOID);
  btnEvent = jswrap_interface_setWatch(doMeasurementAndWaitForResponse_fn,
                            btn, 
                            options);
  jsvUnLock(doMeasurementAndWaitForResponse_fn);

  /// set up main interval callback for nodes
  JsVar *doMeasurement_fn = jsvNewNativeFunction(doMeasurement, JSWAT_VOID);
  currentInterval = jswrap_interface_setInterval(doMeasurement_fn, INTERVAL, 0);
  jsvUnLock(doMeasurement_fn);

  /// prepare the I2C bus for talking with the Si7050 temp sensor
  JsVar *s = jspEvaluate("I2C1.setup({scl:B8, sda:B9, bitrate:50000});"); jsvUnLock(s);
  disableDASH();
  jswrap_interface_setDeepSleep(true); //do deep sleep [TODO can we wake on press?]
#endif
}