Sunday 9 July 2017

0x3fff binary options


Opções binárias Broker Apesar de opções binárias são uma forma relativamente nova de comércio dentro do mercado de ações e outros mercados financeiros, é uma área em rápido crescimento dos mercados de investimento. Os comerciantes experientes são dabbling com esta técnica e abriu a porta para que muitos comerciantes do principiante investem nos mercados. No entanto, é essencial compreender os processos e riscos associados a este tipo de negociação. As opções binárias transformaram-se um navio negociando legal em 2008 em que os Estados Unidos o reconheceram como uma maneira válida, embora diferente de negociar na troca conservada em estoque. É reconhecido como uma das maneiras mais fáceis para qualquer um começar a negociar especialmente aqueles sem experiência. Quando você troca em opções binárias você nunca possui uma mercadoria ou ativo. Em vez disso, você está especulando sobre se o preço de um ativo específico geralmente definido pelo preço da ação, vai para cima ou para baixo dentro de um período de tempo definido. Na verdade, você está apostando ou fazendo uma previsão sobre o movimento do preço de um determinado ativo de você obtê-lo direito você ganhar dinheiro, se não, você perde dinheiro. Cada especulação é geralmente muito curto prazo. Há uma boa quantidade de informações fornecidas a você antes do comércio, se você usar o software online ou um corretor de opções binário aprovado. Em essência, você escolhe um ativo e decidir se o preço vai para cima ou para baixo você não pode hedge suas apostas e espero que ele vai ficar o mesmo Isso torna o conceito de seu investimento muito simples ou o preço se move na direção que você diz que você vai Obter um retorno sobre o seu investimento, ou, ele se move o caminho oposto e você não recebe nada. Depois de ter escolhido o seu activo, em seguida, o seu corretor de opções binárias irá dizer-lhe a percentagem de retorno que você receberá se você estiver correto. Em seguida, você precisa escolher o prazo para sua especulação e quanto dinheiro você está disposto a cometer. Depois de ter decidido todos esses fatores e você está feliz com a sua decisão, iniciar o comércio, selecionando executar em sua tela. A negociação de opção binária de espera e espera é uma das poucas áreas de investimento onde você vai saber exatamente o que seu retorno será fornecer o preço das ações se move na direção certa. Você também está aberto para negociação em uma enorme variedade de mercados se moeda, ações ou commodities o princípio é o mesmo em todos os mercados. De fato, as opções binárias são uma das maneiras mais fáceis de negociar nos mercados internacionais sem precisar de várias contas de corretagem e complicar seus investimentos. Apenas 3 etapas simples a seu sucesso Registre-se e obtenha um presente Fund sua conta de troca e obtenha um sentido do mercado do bônus Predict e ganhe o PASSO 1 - Registre-se e obtenha um Registo do presente tomará menos de um minuto. Você receberá imediatamente sua conta de negociação e todas as ferramentas necessárias para uma negociação bem-sucedida. Nós avaliamos altamente sua escolha. É por isso que preparamos os presentes para você: aulas de vídeo de opções binárias. PASSO 2 - Financiar sua Conta de Negociação e obter um Bônus Você pode financiar uma conta logo após o registro. Estes são os serviços de financiamento mais populares, que lidam conosco: Ao financiar uma conta de negociação, você pode obter os fundos adicionais como um bônus. Ao investir mais, o seu bônus pode ser mesmo dobrado Mac, PC, tablet ou qualquer smartphone mais de 100 ativos disponíveis para negociação. De qualquer dispositivo, a qualquer momento e com um alto nível de segurança. Criando estas plataformas de negociação, nós trabalhamos cada detalhe, a fim de lhe fornecer as condições confortáveis ​​para multiplicar o seu sucesso Garantias retiradas processamento dentro de 1 hora Possibilidade de comércio durante fins de semana Ampla gama de métodos de financiamento e retiradas 100 garantidos de negociação com os dados Finpari 2016. Finpari Todos os direitos reservados Ao negociar opções binárias como com quaisquer ativos financeiros, há uma possibilidade que você pode sustentar um Perda parcial ou total de seus fundos de investimento na negociação. Como resultado, é expressamente aconselhado que você nunca deve investir com, ou negociar sobre, o dinheiro que você não pode dar ao luxo de perder através desta forma de negociação. A Finpari não oferece garantias de lucro nem evita perdas na negociação. O Website eo Conteúdo podem estar disponíveis em vários idiomas. A versão em inglês é a versão original e a única que vincula a Finpari prevalecerá sobre qualquer outra versão em caso de discrepância. A Finpari não será responsável por quaisquer traduções errôneas, inadequadas ou enganosas da versão original para outras línguas. A Finpari, nem os seus agentes ou parceiros não estão registados e não prestam quaisquer serviços no território dos EUA. Sobre a nossa empresa . ,. . ,. . . . . 24opção,,,. ,. C,, (),,. ,,. - benzóico. - benzóico. . CySECParticle Device Firmware Cloud Funções Particle. variable () Expor uma variável através do Cloud para que possa ser chamado com GET / v1 / devices / /. Retorna um valor de sucesso - true quando a variável foi registrada. Até 20 variáveis ​​de nuvem podem ser registradas e cada nome de variável é limitado a um máximo de 12 caracteres. É bom chamar essa função quando a nuvem é desconectada - a variável será registrada na próxima vez em que a nuvem estiver conectada. Antes do firmware 0.4.7, as variáveis ​​foram definidas com um terceiro parâmetro adicional para especificar o tipo de dados da variável. A partir de 0,4,7, o sistema pode inferir o tipo a partir da variável real. Além disso, o endereço da variável foi passado através do endereço do operador (amp). Com 0,4,7 e mais recente, isso não é mais necessário. Esta é a sintaxe pré-0.4.7: Existem três tipos de dados suportados: INT DOUBLE STRING (comprimento máximo da cadeia é 622 bytes) Particle. function () Expor uma função através da Cloud para que possa ser chamada com POST / v1 / Dispositivos / /. Até 15 funções de nuvem podem ser registradas e cada nome de função é limitado a um máximo de 12 caracteres. Para registrar uma função de nuvem, o usuário fornece o funcKey. Que é o nome de seqüência de caracteres usado para fazer uma solicitação POST e um funcName. Que é o nome real da função que é chamada no seu aplicativo. A função de nuvem pode retornar qualquer inteiro -1 é comumente usado para uma chamada de função com falha. Uma função de nuvem é configurada para ter um argumento do tipo de dados String. Esse comprimento de argumento é limitado a um máximo de 63 caracteres. Você pode expor um método em um objeto C para a Nuvem. A solicitação de API será encaminhada para o dispositivo e executará sua função brew. A resposta terá uma chave returnvalue contendo o inteiro retornado por brew. Particle. publish () Publicar um evento através do Cloud de Partículas que será encaminhado para todos os ouvintes registrados, como callbacks, fluxos assinados de Server-Sent Events e outros dispositivos escutando via Particle. subscribe (). Esse recurso permite que o dispositivo gere um evento com base em uma condição. Por exemplo, você pode conectar um sensor de movimento ao dispositivo e fazer com que o dispositivo gere um evento sempre que for detectado movimento. Os eventos de nuvem têm as seguintes propriedades: nome (163 caracteres ASCII) público / privado (público padrão) ttl (tempo de vida, 016777215 segundos, padrão 60). NOTA: O valor ttl especificado pelo utilizador ainda não foi implementado, por isso alterar esta propriedade não terá actualmente qualquer impacto. Dados opcionais (até 255 bytes) Qualquer um pode se inscrever em eventos públicos, pense neles como tweets. Apenas o proprietário do dispositivo poderá subscrever eventos privados. Um dispositivo não pode publicar eventos que comecem com uma correspondência entre maiúsculas e minúsculas para faísca. Tais eventos são reservados para dados oficialmente curados originários da Nuvem. Chamar Particle. publish () quando o dispositivo não está conectado à nuvem não resultará em um evento sendo publicado. Isto é indicado pelo código de sucesso de retorno de false. Por enquanto, não existe maneira de acessar um evento publicado anteriormente, mas TTL-unexpired. NOTA: Actualmente, um dispositivo pode publicar a uma taxa de cerca de 1 evento / seg, com rajadas de até 4 permitidos em 1 segundo. Ruptura de 4 mensagens de volta para trás levará 4 segundos para recuperar. Publicar um evento público com o nome fornecido, sem dados e o TTL padrão de 60 segundos. Publicar um evento público com o nome e os dados fornecidos, com o TTL padrão de 60 segundos. Publicar um evento público com o nome fornecido, dados e TTL. Publicar um evento privado com o nome fornecido, dados e TTL. Para publicar um evento privado, você deve passar todos os quatro parâmetros. Publicar um evento privado com o nome fornecido. Particle. subscribe () Assinar eventos publicados por dispositivos. Isso permite que os dispositivos para conversar entre si muito facilmente. Por exemplo, um dispositivo pode publicar eventos quando um sensor de movimento é acionado e outro pode assinar esses eventos e responder soando um alarme. Para usar Particle. subscribe (). Definir uma função de manipulador e registrá-lo em setup (). Você pode ouvir eventos publicados apenas por seus próprios dispositivos, adicionando uma constante MYDEVICES. Você pode registrar um método em um objeto C como um manipulador de inscrição. Uma assinatura funciona como um filtro de prefixo. Se você se inscrever no foo, você receberá qualquer evento cujo nome comece com foo, incluindo foo, fool, foobar e food / indian / sweet-curry-beans. Eventos recebidos serão passados ​​para uma função de manipulador semelhante a Particle. function (). Um manipulador de inscrição (como o myHandler acima) deve retornar void e ter dois argumentos, ambos são strings C (const char). O primeiro argumento é o nome completo do evento publicado. O segundo argumento (que pode ser NULL) é qualquer dado que veio junto com o evento. Particle. subscribe () retorna um bool indicando sucesso. É ok para registrar uma assinatura quando o dispositivo não está conectado à nuvem - a assinatura é automaticamente registrada com a nuvem próxima vez que o dispositivo se conecta. NOTA: Um dispositivo pode registrar até 4 manipuladores de eventos. Isso significa que você pode chamar Particle. subscribe () um máximo de 4 vezes depois que ele retornará false. Particle. unsubscribe () Remove todos os manipuladores de assinatura anteriormente registrados com Particle. subscribe (). Particle. connect () Particle. connect () conecta o dispositivo à nuvem. Isso ativará automaticamente o módulo Wi-Fi e tentará se conectar a uma rede Wi-Fi se o dispositivo ainda não estiver conectado a uma rede. Depois de chamar Particle. connect (). Seu loop não será chamado novamente até que o dispositivo termine de se conectar à Nuvem. Normalmente, você pode esperar um atraso de aproximadamente um segundo. Na maioria dos casos, você não precisa chamar Particle. connect () ele é chamado automaticamente quando o dispositivo é ligado. Normalmente, você só precisa chamar Particle. connect () depois de desconectar com Particle. disconnect () ou quando você altera o modo de sistema. Particle. disconnect () Particle. disconnect () desconecta o dispositivo da Nuvem. Enquanto esta função se desligar da Nuvem, ela manterá a conexão com a rede Wi-Fi. Se você deseja desativar completamente o módulo Wi-Fi, use WiFi. off (). NOTA: Quando o dispositivo é desconectado, muitos recursos não são possíveis, incluindo atualizações over-the-air, variáveis ​​de partículas de leitura e chamar Particle. functions. Se você se desconectar da Nuvem, NÃO será capaz de piscar novo firmware sobre o ar. Uma redefinição de fábrica deve resolver o problema. Particle. connected () Retorna true quando conectado ao Cloud, e false quando desconectado da Cloud. Particle. process () Executa o loop de plano de fundo. Esta é a API pública para a função interna anterior SPARKWLANLoop (). O Particle. process () verifica o módulo Wi-Fi para receber mensagens da Nuvem e processa todas as mensagens que chegaram. Ele também envia pings keep-alive para a Nuvem, então se não for chamado com frequência, a conexão com a Nuvem Pode ser perdida. Mesmo em aplicações não ligadas à nuvem, ainda é aconselhável chamar Particle. process () para fornecer explicitamente algum tempo de processador ao módulo Wi-Fi (por exemplo, imediatamente após WiFi. ready () para atualizar variáveis ​​de sistema). Particle. process () é uma chamada de bloqueio e bloqueia por alguns milissegundos. Particle. process () é chamado automaticamente após cada loop () e durante os atrasos. Normalmente, você não precisará chamar Particle. process () a menos que você bloqueie de alguma outra maneira e precise manter a conexão com a Nuvem, ou alterar o modo de sistema. Se o usuário colocar o dispositivo no modo MANUAL, o usuário é responsável por chamar Particle. process (). Quanto mais freqüentemente essa função for chamada, quanto mais responsivo for o dispositivo para as mensagens de entrada, maior será a probabilidade de a conexão em nuvem permanecer aberta e menor a probabilidade de que o buffer de módulos Wi-Fi seja excedido. Particle. syncTime () Sincronize o tempo com a nuvem de partículas. Isso acontece automaticamente quando o dispositivo se conecta à Nuvem. No entanto, se o seu dispositivo é executado continuamente por um longo tempo, você pode querer sincronizar uma vez por dia ou assim. Observe que essa função envia uma mensagem de solicitação para o Cloud e, em seguida, retorna. A hora no dispositivo não será sincronizada até alguns milissegundos mais tarde, quando a nuvem responde com o tempo atual entre as chamadas para seu loop. Obter IP Público Usando esse recurso, o dispositivo pode saber programaticamente seu próprio endereço IP público. Obter o nome do dispositivo Isto lhe dá o nome do dispositivo que está armazenado na nuvem, Obter sementes aleatórias Pegar 40 bytes de aleatoriedade da nuvem e n r p away WiFi on () WiFi. on () liga o módulo Wi-Fi. Útil quando você o desligou e você mudou de idéia. Observe que WiFi. on () não precisa ser chamado a menos que você tenha alterado o modo de sistema ou você tenha desligado o módulo Wi-Fi antes. Off () WiFi. off () desliga o módulo Wi-Fi. Útil para poupar energia, uma vez que a maior parte do consumo de energia do dispositivo é o módulo Wi-Fi. Connect () Tentativas de conexão à rede Wi-Fi. Se não houver credenciais armazenadas, isso entrará no modo de audição (veja abaixo como evitar isso.). Se houver credenciais armazenadas, isso tentará as credenciais disponíveis até que a conexão seja bem-sucedida. Quando esta função retorna, o dispositivo pode não ter um endereço IP na LAN use WiFi. ready () para determinar o status da conexão. Desde 0.4.5 É possível chamar WiFi. connect () sem entrar no modo de escuta no caso em que nenhuma credencial é armazenada: Se não houver credenciais, então a chamada não faz nada além de ativar o módulo WiFi. Disconnect () Desconecta da rede Wi-Fi, mas deixa o módulo Wi-Fi ligado. Connecting () Esta função retornará true quando o dispositivo estiver tentando se conectar usando credenciais de Wi-Fi armazenadas e retornará false uma vez que o dispositivo tenha se conectado com êxito à rede Wi-Fi. Ready () Esta função retornará true quando o dispositivo estiver conectado à rede e tiver sido atribuído um endereço IP, o que significa que seus pronta para abrir soquetes TCP e enviar datagramas UDP. Caso contrário, ele retornará false. SelectAntenna () Selecciona qual antena o dispositivo deve ligar ao Wi-Fi com e memoriza essa definição até ser alterada. WiFi. selectAntenna () seleciona um dos três modos de antena no seu Photon ou P1. É preciso um argumento: ANTAUTO. ANTINTERNO ou ANTEXTERNO. WiFi. selectAntenna () deve ser usado dentro de outra função como STARTUP (), setup () ou loop () para compilar. Você pode especificar no código qual antena usar como o padrão no tempo de inicialização usando a macro STARTUP (). Observe que a seleção da antena é lembrada mesmo após o desligamento ou quando entrar no modo de segurança. Isso permite que seu dispositivo seja configurado uma vez e, em seguida, continuar a funcionar com a antena selecionada quando as aplicações são piscadas que não especificam qual antena usar. Isto assegura que os dispositivos que devem utilizar a antena externa continuem a utilizar a antena externa em todos os casos mesmo quando o código da aplicação não está a ser executado (por exemplo, modo seguro.) Se nenhuma antena tiver sido previamente seleccionada, a antena ANTINTERNAL será escolhida por defeito. WiFi. selectAntenna () retorna 0 em caso de sucesso, ou -1005 se a escolha da antena não foi encontrada. Outros erros que podem aparecer serão todos valores negativos. Listen () Isto irá entrar ou sair do modo de escuta, que abre uma conexão Serial para obter credenciais de Wi-Fi por USB e também escuta as credenciais do Soft AP. O modo de escuta bloqueia o código do aplicativo. Os casos avançados que usam multithreading, interrupções ou eventos do sistema têm a capacidade de continuar a executar o código do aplicativo enquanto estiver no modo de audição e podem desejar sair do modo de escuta, como após um tempo limite. O modo de escuta é parado usando esta sintaxe: listening () Agora, este comando não é útil, sempre retornando false. Porque o modo de audição bloqueia o código do aplicativo. Este comando se torna útil no Photon e Electron quando o código do sistema é executado como uma tarefa RTOS separada do código do aplicativo. Nós estimamos que o recurso de firmware será lançado para o Photon em setembro de 2015. Uma vez que o código do sistema não bloquear o código do aplicativo, WiFi. listening () retornará true uma vez que o WiFi. listen () foi chamado ou o botão de configuração foi mantido por 3 Segundos, quando o LED RGB estiver piscando em azul. Ele retornará falso quando o dispositivo não estiver no modo de audição. SetCredentials () Permite que o aplicativo defina credenciais para a rede Wi-Fi de dentro do código. Essas credenciais serão adicionadas à memória dos dispositivos e o dispositivo tentará automaticamente conectar-se a esta rede no futuro. Seu dispositivo pode se lembrar de mais de um conjunto de credenciais: Core: lembra as 7 credenciais mais recentemente definidas Photon: lembra as 5 credenciais mais recentemente definidas Quando o Photon usado com redes ocultas ou off-line, a cifra de segurança também é necessária. Nota: Para que WiFi. setCredentials () funcione, o módulo WiFi precisa estar ligado (se desligado ou desabilitado via nonAUTOMATIC SYSTEMMODEs, ligue para WiFi. on ()). GetCredentials () Lista as redes Wi-Fi com credenciais armazenadas no dispositivo. Retorna o número de redes armazenadas. Observe que isso retorna detalhes sobre as redes Wi-Fi, mas não a senha real. ClearCredentials () Isso limpará todas as credenciais salvas da memória dos módulos Wi-Fi. Isso retornará true em caso de sucesso e false se o módulo Wi-Fi tiver um erro. HasCredentials () Retornará true se houver credenciais Wi-Fi armazenadas na memória dos módulos Wi-Fi. MacAddress () WiFi. macAddress () retorna o endereço MAC do dispositivo. SSID () WiFi. SSID () retorna o SSID da rede ao qual o dispositivo está atualmente conectado como um char. BSSID () WiFi. BSSID () retorna o endereço MAC de 6 bytes do ponto de acesso ao qual o dispositivo está atualmente conectado. Void setup () WiFi. BSSID (bssid) Serial. printlnf RSSI () WiFi. RSSI () retorna a intensidade do sinal De uma rede Wi-Fi de -127 (fraco) para -1dB (forte) como um int. Valores de retorno positivo indicam um erro com 1 indicando um erro de chip Wi-Fi e 2 indicando um erro de tempo limite. Ping () WiFi. ping () permite ping um endereço IP e retorna o número de pacotes recebidos como um int. É preciso duas formas: WiFi. ping (IPAddress remoteIP) tem um IPAddress e pings esse endereço. WiFi. ping (IPAddress remoteIP, uint8t nTries) e pings que endereço um número especificado de vezes. Scan () Retorna informações sobre pontos de acesso dentro do alcance do dispositivo. A primeira forma é a mais simples, mas também menos flexível. Você fornece uma matriz de instâncias WiFiAccessPoint e a chamada para WiFi. scan () preenche a matriz. Se houver mais APs detectados do que cabem na matriz, eles são descartados. Retorna o número de pontos de acesso gravados na matriz. A chamada mais avançada para WiFi. scan () usa uma função de retorno de chamada que recebe cada ponto de acesso digitalizado. A principal razão para fazer isso é que você ganha acesso a todos os pontos de acesso disponíveis sem ter que saber antecipadamente quantos pode haver. Você também pode passar um segundo parâmetro para WiFi. scan () após o retorno de chamada, que permite que o código orientado a objeto para ser usado. Resolve () WiFi. resolve () localiza o endereço IP de um nome de domínio. nome. O nome do domínio para resolver (string) Retorna o endereço IP se o nome do domínio for encontrado, caso contrário, um endereço IP em branco. LocalIP () WiFi. localIP () retorna o endereço IP local atribuído ao dispositivo como um IPAddress. SubnetMask () WiFi. subnetMask () retorna a máscara de sub-rede da rede como um IPAddress. GatewayIP () WiFi. gatewayIP () retorna o endereço IP de gateway da rede como um IPAddress. DnsServerIP () WiFi. dnsServerIP () recupera o endereço IP do servidor DNS que resolve as solicitações de DNS para a conexão de rede dos dispositivos. Observe que, para que esse valor esteja disponível, é necessário chamar Particle. process () após a conexão do Wi-Fi. DhcpServerIP () WiFi. dhcpServerIP () recupera o endereço IP do servidor DHCP que gerencia o endereço IP usado pela conexão de rede dos dispositivos. Observe que, para que esse valor esteja disponível, é necessário chamar Particle. process () após a conexão do Wi-Fi. SetStaticIP () Define os endereços IP estáticos usados ​​pelo sistema para se conectar à rede quando o IP estático é ativado. Os endereços são armazenados persistentemente para que eles estejam disponíveis em todas as aplicações subseqüentes e também em modo de segurança. UseStaticIP () Instrui o sistema a se conectar à rede usando os endereços IP fornecidos para WiFi. setStaticIP () A configuração é persistente e é lembrada até que WiFi. useDynamicIP () seja chamado. UseDynamicIP () Instrui o sistema a se conectar à rede usando um endereço IP alocado dinamicamente do roteador. Uma nota sobre a comutação entre IP estático e dinâmico. Se os endereços IP estáticos foram previamente configurados usando WiFi. setStaticIP (). Eles continuam a ser lembrado pelo sistema depois de chamar WiFi. useDynamicIP (). E assim que estão disponíveis para o uso a próxima vez WiFi. useStaticIP () é chamado, sem necessitar ser reconfigured usando WiFi. setStaticIP () SoftAP HTTP Pages Quando o dispositivo está no modo de escuta, cria um ponto de acesso provisório (AP) e um HTTP Na porta 80. O servidor HTTP é usado para configurar os pontos de acesso Wi-Fi aos quais o dispositivo tenta se conectar. Além do sistema que fornece URLs HTTP, os aplicativos podem adicionar suas próprias páginas ao servidor HTTP do SoftAP. SoftAP HTTP Pages é atualmente um recurso avançado, exigindo moderada C conhecimento. Para estar usando o recurso: adicionar pragma SPARKNOPREPROCESSOR para o topo do seu esboço adicionar incluir Particle. h abaixo disso, em seguida, adicionar incluir softaphttp. h abaixo que ainda O softapsetapplicationpagehandler é definido durante a inicialização. Quando o sistema está no modo de configuração e uma solicitação é feita para um URL desconhecido, o sistema chama a função de manipulador de página fornecida pelo aplicativo (aqui, myPages.) A função de manipulador de página é chamada sempre que um URL desconhecido é solicitado. É chamado com estes parâmetros: url. O caminho do arquivo solicitado pelo cliente. Não inclui o nome do servidor ou a porta. Exemplos: / index. /someimage. jpg. Cb. Um retorno de chamada de resposta - usado pelo aplicativo para indicar o tipo de resposta HTTP, como 200 (OK) ou 404 (não encontrado). Mais sobre isso abaixo. CbArg. Dados que devem ser passados ​​como o primeiro parâmetro para a função callback cb. corpo. Um objeto leitor que o manipulador de página usa para recuperar o resultado do corpo de solicitação HTTP. Um objeto de gravador que o manipulador de página usa para gravar o corpo de resposta HTTP reservado. Reservado para futura expansão. Será igual a nullptr e pode ser ignorado. O aplicativo deve chamar a função callback página cb para fornecer uma resposta para a página solicitada. Se a URL da página solicitada não for reconhecida pela aplicação, então uma resposta 404 deve ser enviada, conforme descrito abaixo. A função de retorno de chamada de página Quando a função de manipulador de página é chamada, o sistema passa uma função de retorno de chamada de resultado como o parâmetro cb. A função callback leva esses parâmetros: cbArg. Este é o parâmetro cbArg passado para a função de retorno de chamada de página. Seu estado interno usado pelo servidor HTTP. bandeiras. Actualmente não utilizado. Defina para 0. status. O código de status HTTP, como um número inteiro, como 200 para OK. Ou 404 para página não encontrada. Tipo mime. O mime-tipo da resposta como uma string, como text / html ou application / javascript. cabeçalho. Um ponteiro opcional para um cabeçalho que é adicionado à resposta enviada para o cliente. Por exemplo, para enviar um erro não encontrado para uma página que não é reconhecida, o código do aplicativo chamaria Recuperando os dados da solicitação Quando a solicitação HTTP contém um corpo de solicitação (como com uma solicitação POST), o objeto Reader fornecido pelo corpo Pode ser usado para recuperar os dados da solicitação. Enviando uma resposta Ao enviar uma página, a função de página responde com um código HTTP 200, significando que o conteúdo foi encontrado, seguido pelos dados da página. A página padrão Quando um navegador solicita a página padrão (192.168.0.1/), o sistema internamente redireciona isso para / index para que possa ser manipulado pela aplicação. O aplicativo pode fornecer uma página real em / index ou redirecionar para outra página se o aplicativo pefers para ter outra página como sua página de inicialização. Enviando um redirecionamento O aplicativo pode enviar uma resposta de redirecionamento para uma determinada página, a fim de gerenciar o espaço de nomes de URL, como fornecer aliases para alguns recursos. O código abaixo envia um redirecionamento da página padrão / índice para / index Exemplo completo Heres um exemplo completo fornecendo uma interface de usuário da Web para configurar o WiFi via HTTP. O pinMode () pinMode () configura o pino especificado para se comportar como uma entrada (com ou sem uma resistência pull-up ou pull-down interna fraca) ou uma saída. PinMode () leva dois argumentos, pino. O número do pino cujo modo você deseja definir e modo. INPUT, INPUTPULLUP, INPUTPULLDOWN ou OUTPUT. PinMode () não retorna nada. GetPinMode (pino) Recupera o modo de pino atual. DigitalWrite () Escreva um valor HIGH ou LOW em um pino digital. Se o pino tiver sido configurado como OUTPUT com pinMode () ou se anteriormente utilizado com analogWrite (). Sua tensão será ajustada para o valor correspondente: 3.3V para HIGH, 0V (terra) para LOW. DigitalWrite () leva dois argumentos, pino. O número do pino cujo valor você deseja definir e valor. ALTO ou BAIXO. DigitalWrite () não retorna nada. Nota: Todos os pinos GPIO (D0, D7, A0, A7, DAC, WKP, RX, TX) podem ser utilizados desde que não sejam utilizados de outra forma (por exemplo, como Serial1 RX / TX). DigitalRead () Lê o valor de um pino digital especificado. Ou ALTO ou BAIXO. DigitalRead () leva um argumento, pino. O número do pino digital que deseja ler. DigitalRead () retorna HIGH ou LOW. Nota: Todos os pinos GPIO (D0, D7, A0, A7, DAC, WKP, RX, TX) podem ser utilizados desde que não sejam utilizados de outra forma (por exemplo, como Serial1 RX / TX). AnalogWrite () (PWM) Grava um valor analógico para um pino como um sinal digital PWM (pulso-largura modulada). A freqüência padrão do sinal PWM é de 500 Hz. Pode ser usado para acender um LED em variações de luminosidade ou conduzir um motor a várias velocidades. Depois de uma chamada para analogWrite (), o pino irá gerar uma onda quadrada constante do ciclo de trabalho especificado até a próxima chamada para analogWrite () (ou uma chamada para digitalRead () ou digitalWrite () no mesmo pino). AnalogWrite () leva dois ou três argumentos: pin. O número do pino cujo valor você deseja definir valor. O ciclo de trabalho: entre 0 (sempre desligado) e 255 (sempre ligado). Desde 0.6.0: entre 0 e 255 (resolução padrão de 8 bits) ou 2 (analogWriteResolution (pin)) - 1 em geral. freqüência. A freqüência PWM: entre 1 Hz e 65535 Hz (padrão 500 Hz). Desde 0.6.0: entre 1 Hz e analogWriteMaxFrequency (pino). NOTA: pinMode (pino, OUTPUT) é necessário antes de chamar analogWrite (pino, valor) ou então o pino não será inicializado como uma saída PWM e ajustado para o ciclo de trabalho desejado. AnalogWrite () não retorna nada. No núcleo, esta função funciona nos pinos D0, D1, A0, A1, A4, A5, A6, A7, RX e TX. No Photon e no Electron, esta função funciona nos pinos D0, D1, D2, D3, A4, A5, WKP, RX e TX com uma advertência: o periférico do temporizador PWM é duplicado em dois pinos (A5 / D2) e (A4 / D3 ) Para 7 saídas PWM independentes. Por exemplo: PWM pode ser usado em A5 enquanto D2 é usado como um GPIO, ou D2 como um PWM enquanto A5 é usado como uma entrada analógica. No entanto, A5 e D2 não podem ser utilizados como saídas PWM controladas independentemente ao mesmo tempo. Adicionalmente no Electron, esta função funciona nos pinos B0, B1, B2, B3, C4, C5. A freqüência PWM deve ser a mesma para pinos no mesmo grupo de temporizador. No núcleo, os grupos do temporizador são D0 / D1, A0 / A1 / RX / TX, A4 / A5 / A6 / A7. No Photon, os grupos do temporizador são D0 / D1, D2 / D3 / A4 / A5, WKP, RX / TX. No P1, os grupos de temporização são D0 / D1, D2 / D3 / A4 / A5 / P1S0 / P1S1, WKP, RX / TX. No Electron, os grupos do temporizador são D0 / D1 / C4 / C5, D2 / D3 / A4 / A5 / B2 / B3, WKP, RX / TX, B0 / B1. NOTA: Quando usado com pinos compatíveis com PWM, a função analogWrite () configura esses pinos somente como PWM. Esta função funciona de forma diferente quando usada com os pinos de saída analógica (DAC). AnalogWriteResolution () (PWM e DAC) Define ou recupera a resolução da função analogWrite () de um determinado pino. AnalogWriteResolution () toma um ou dois argumentos: pin. O número do pino cuja resolução você deseja definir ou recuperar a resolução. (Opcional) resolução em bits. O valor pode variar de 2 a 31 bits. Se a resolução não for suportada, ela não será aplicada. AnalogWriteResolution () retorna a resolução atualmente definida. NOTA: Os pinos DAC1 (A6) e DAC2 (A3) do DAC suportam apenas resoluções de 8 bits ou de 12 bits (predefinição). NOTA: A resolução também afeta a freqüência máxima que pode ser usada com analogWrite (). A freqüência máxima permitida com a resolução atual pode ser verificada chamando analogWriteMaxFrequency (). AnalogWriteMaxFrequency () (PWM) Retorna a freqüência máxima que pode ser usada com analogWrite () neste pino. AnalogWriteMaxFrequency () tem um argumento: pino. O número da saída analógica do pino (DAC) O Photon e o Electron suportam a saída analógica verdadeira nos pinos DAC (DAC1 ou A6 no código) e A3 (DAC2 ou A3 no código). Usando o analogWrite (pino, valor) com estes pinos, a saída do pino é ajustada para uma tensão analógica de 0V a 3.3V que corresponde a valores de 0-4095. NOTA: Esta saída é tamponado no interior do STM32 para permitir mais corrente de saída com o custo de não ser capaz de conseguir o desempenho rail-to-rail, ou seja, a saída será de cerca de 50 mV quando o DAC é definido como 0, e aproximadamente 50 mV menos que a tensão 3V3 quando a saída DAC está definido para 4095. NOTA: Sistema de firmware versão 0.4.6 e 0.4.7 única - não se aplica a versões de 0.4.9 em diante: Enquanto para PWM pinos de uma única chamada para pinMode (pin, oUTPUT) Define o modo pino para várias chamadas analógica (pino, valor), para pinos DAC você precisa definir pinMode (DAC, OUTPUT) cada vez que você deseja executar um analogWrite (). AnalogRead () (ADC) Lê o valor do pino analógico especificado. O dispositivo tem 8 canais (A0 a A7) com uma resolução de 12 bits. Isso significa que ele irá mapear tensões de entrada entre 0 e 3,3 volts em valores inteiros entre 0 e 4095. Isso produz uma resolução entre as leituras de: 3,3 volts / 4096 unidades ou, 0,0008 volts (0,8 mV) por unidade. Antes de 0.5.3 Nota. Não defina o pinMode () com analogRead (). O pinMode () é automaticamente definido como ANINPUT na primeira vez em que analogRead () é chamado para um determinado pino analógico. Se você definir explicitamente um pino para INPUT ou OUTPUT após essa primeira utilização de analogRead (), ele não tentará alterá-lo novamente para ANINPUT na próxima vez que você chamar analogRead () para o mesmo pino analógico. Isso criará leituras analógicas incorretas. Desde 0,5.3 Nota: você não precisa definir o pinMode () com analogRead (). O pinMode () é automaticamente ajustado para ANINPUT sempre que analogRead () for chamado para um pino analógico particular, se esse pino estiver configurado para um pinMode diferente de ANINPUT. Se você definir explicitamente um pino para INPUT, INPUTPULLUP, INPUTPULLDOWN ou OUTPUT antes de usar analogRead (), ele irá alterá-lo novamente para ANINPUT antes de fazer a leitura. Se você usar digitalRead () depois, ele irá alternar automaticamente o pinMode de volta para o que você originalmente explicitamente definido para ele. AnalogRead () leva um pino de argumento. o número do pino de entrada analógico para ler a partir de (A0 a A7.) analogRead () retorna um valor inteiro variando de 0 a 4095. setADCSampleTime () A função setADCSampleTime (duração) é utilizado para alterar o tempo de amostragem padrão para analogRead () . Por Core, este parâmetro pode ser um dos seguintes valores: ADCSampleTime1Cycles5: Tempo da amostra igual a 1,5 ciclos ADCSampleTime7Cycles5: tempo da amostra igual a 7,5 ciclos ADCSampleTime13Cycles5: tempo da amostra igual a 13,5 ciclos ADCSampleTime28Cycles5: tempo da amostra igual a 28,5 ciclos ADCSampleTime41Cycles5: Tempo da amostra igual a 41,5 ciclos ADCSampleTime55Cycles5: tempo da amostra igual a 55,5 ciclos ADCSampleTime71Cycles5: tempo da amostra igual a 71,5 ciclos ADCSampleTime239Cycles5: tempo da amostra igual a 239,5 ciclos na fótons e de elétrons, este parâmetro pode ser um dos seguintes valores: ADCSampleTime3Cycles: tempo da amostra igual a 3 ciclos ADCSampleTime15Cycles: tempo da amostra igual a 15 ciclos ADCSampleTime28Cycles: tempo da amostra igual a 28 ciclos ADCSampleTime56Cycles: tempo da amostra igual a 56 ciclos ADCSampleTime84Cycles: tempo da amostra igual a 84 ciclos ADCSampleTime112Cycles: tempo da amostra igual a 112 ciclos ADCSampleTime144Cycles: tempo da amostra igual a 144 ciclos ADCSampleTime480Cycles: tempo da amostra igual a 480 ciclos de Baixo Nível de Entrada / saída o Input / funções oUPUT incluem verificações de segurança, tais como certificando-se de um pino é definido como OUTPUT ao fazer uma digitalWrite () ou que o pino não está sendo usado para uma função timer. Essas medidas de segurança representam uma boa codificação e prática de projeto do sistema. Há momentos em que as operações de entrada / saída mais rápidas são cruciais para o desempenho de uma aplicação. O hardware SPI, UART (Serial) ou I2C são exemplos de dispositivos orientados a desempenho de baixo nível. Há, no entanto, momentos em que estes dispositivos podem não ser adequados ou disponíveis. Por exemplo, o suporte One-wire é feito em software, não em hardware. Para fornecer o E / S bit-oriented mais rápido possível, as verificações de segurança normais devem ser ignoradas. Como tal, lembre-se de que o programador é responsável pelo bom planejamento e uso das funções de E / S de baixo nível. Antes de usar as seguintes funções de baixo nível, pinMode () deve ser usado para configurar o pino de destino. PinSetFast () Escreva um valor HIGH para um pino digital. PinSetFast () tem um argumento, pino. O número do pino cujo valor você deseja ajustar HIGH. PinSetFast () não retorna nada. PinResetFast () Escreva um valor LOW para um pino digital. PinResetFast () tem um argumento, pino. O número do pino cujo valor você deseja definir LOW. PinResetFast () não retorna nada. DigitalWriteFast () Escreva um valor HIGH ou LOW para um pino digital. Esta função chamará pinSetFast () ou pinResetFast () com base no valor e é útil quando o valor é calculado. Como tal, isso impõe uma ligeira sobrecarga de tempo. DigitalWriteFast (). O número do pino cujo valor você deseja definir e valor. ALTO ou BAIXO. DigitalWriteFast () não retorna nada. PinReadFast () Lê o valor de um pino digital especificado. Ou ALTO ou BAIXO. PinReadFast () tem um argumento, pino. O número do pino digital que deseja ler. PinReadFast () retorna HIGH ou LOW. Tom de E / S avançado () Gera uma onda quadrada da freqüência e duração especificadas (e ciclo de 50 ciclos) em um pino de canal de temporização que suporta PWM. O uso da função tone () interferirá com a saída PWM no pino selecionado. No núcleo, esta função funciona nos pinos D0, D1, A0, A1, A4, A5, A6, A7, RX e TX. No Photon e no Electron, esta função funciona nos pinos D0, D1, D2, D3, A4, A5, WKP, RX e TX com uma advertência: O periférico do temporizador de tonalidade é duplicado em dois pinos (A5 / D2) e (A4 / D3 ) Para 7 saídas de Tone independentes. Por exemplo: Tone pode ser usado em A5 enquanto D2 é usado como um GPIO, ou D2 para Tone enquanto A5 é usado como uma entrada analógica. No entanto, A5 e D2 não podem ser utilizados como saídas de Tone independentes ao mesmo tempo. Adicionalmente no Electron, esta função funciona nos pinos B0, B1, B2, B3, C4, C5. Tom () leva três argumentos, pino. O pino em que para gerar o tom, a freqüência. the frequency of the tone in hertz and duration. the duration of the tone in milliseconds (a zero value continuous tone). The frequency range is from 20Hz to 20kHz. Frequencies outside this range will not be played. tone() does not return anything. NOTE: the Photons PWM pins / timer channels are allocated as per the following table. If multiple, simultaneous tone() calls are needed (for example, to generate DTMF tones), use pins allocated to separate timers to avoid stuttering on the output: noTone() Stops the generation of a square wave triggered by tone() on a specified pin (D0, D1, A0, A1, A4, A5, A6, A7, RX, TX). Has no effect if no tone is being generated. noTone() takes one argument, pin. the pin on which to stop generating the tone. noTone() does not return anything. shiftOut() Shifts out a byte of data one bit at a time on a specified pin. Starts from either the most (i. e. the leftmost) or least (rightmost) significant bit. Each bit is written in turn to a data pin, after which a clock pin is pulsed (taken high, then low) to indicate that the bit is available. NOTE: if youre interfacing with a device thats clocked by rising edges, youll need to make sure that the clock pin is low before the call to shiftOut(). por exemplo. with a call to digitalWrite(clockPin, LOW) . This is a software implementation see also the SPI function, which provides a hardware implementation that is faster but works only on specific pins. shiftOut() takes four arguments, dataPin: the pin on which to output each bit, clockPin. the pin to toggle once the dataPin has been set to the correct value, bitOrder. which order to shift out the bits either MSBFIRST or LSBFIRST (Most Significant Bit First, or, Least Significant Bit First) and value. the data (byte) to shift out. shiftOut() does not return anything. shiftIn() Shifts in a byte of data one bit at a time. Starts from either the most (i. e. the leftmost) or least (rightmost) significant bit. For each bit, the clock pin is pulled high, the next bit is read from the data line, and then the clock pin is taken low. NOTE: if youre interfacing with a device thats clocked by rising edges, youll need to make sure that the clock pin is low before the call to shiftOut(), e. g. with a call to digitalWrite(clockPin, LOW) . This is a software implementation see also the SPI function, which provides a hardware implementation that is faster but works only on specific pins. shiftIn() takes three arguments, dataPin: the pin on which to input each bit, clockPin. the pin to toggle to signal a read from dataPin, bitOrder. which order to shift in the bits either MSBFIRST or LSBFIRST (Most Significant Bit First, or, Least Significant Bit First). shiftIn() returns the byte value read. pulseIn() Reads a pulse (either HIGH or LOW) on a pin. For example, if value is HIGH, pulseIn() waits for the pin to go HIGH, starts timing, then waits for the pin to go LOW and stops timing. Returns the length of the pulse in microseconds or 0 if no complete pulse was received within the timeout. The timing of this function is based on an internal hardware counter derived from the system tick clock. Resolution is 1/Fosc (1/72MHz for Core, 1/120MHz for Photon/P1/Electron). Works on pulses from 10 microseconds to 3 seconds in length. Please note that if the pin is already reading the desired value when the function is called, it will wait for the pin to be the opposite state of the desired value. and then finally measure the duration of the desired value. This routine is blocking and does not use interrupts. The pulseIn() routine will time out and return 0 after 3 seconds. pulseIn() takes two arguments, pin. the pin on which you want to read the pulse (this can be any GPIO, e. g. D1, A2, C0, B3, etc..), value. type of pulse to read: either HIGH or LOW. pin should be set to one of three pinMode() s prior to using pulseIn(), INPUT. INPUTPULLUP or INPUTPULLDOWN . pulseIn() returns the length of the pulse (in microseconds) or 0 if no pulse is completed before the 3 second timeout (unsigned long) Serial Used for communication between the device and a computer or other devices. The device has two serial channels: Serial: This channel communicates through the USB port and when connected to a computer, will show up as a virtual COM port. Serial1: This channel is available via the devices TX and RX pins. Serial2: This channel is optionally available via the devices RGB Green (TX) and Blue (RX) LED pins. The Blue and Green current limiting resistors should be removed. To use Serial2, add include Serial2/Serial2.h near the top of your apps main code file. If the user enables Serial2, they should also consider using RGB. onChange() to move the RGB functionality to an external RGB LED on some PWM pins. To use the hardware serial pins of (Serial1/2) to communicate with your personal computer, you will need an additional USB-to-serial adapter. To use them to communicate with an external TTL serial device, connect the TX pin to your devices RX pin, the RX to your devices TX pin, and the ground of your Core/Photon/Electron to your devices ground. NOTE: Please take into account that the voltage levels on these pins operate at 0V to 3.3V and should not be connected directly to a computers RS232 serial port which operates at /- 12V and will damage the Core/Photon/Electron. begin() Available on Serial, Serial1, Serial2. As of 0.5.0 firmware, 28800 baud set on the Host will put the device in Listening Mode, where a YMODEM download can be started by additionally sending an f character. The configuration of the serial channel may also specify the number of data bits, stop bits, parity, flow control and other settings. The default is SERIAL8N1 (8 data bits, no parity and 1 stop bit) and does not need to be specified to achieve this configuration. To specify one of the following configurations, add one of these defines as the second parameter in the begin() function, e. g. Serial. begin(9600, SERIAL8E1) for 8 data bits, even parity and 1 stop bit. Pre-defined Serial configurations available: SERIAL8N1 - 8 data bits, no parity, 1 stop bit (default) SERIAL8N2 - 8 data bits, no parity, 2 stop bits SERIAL8E1 - 8 data bits, even parity, 1 stop bit SERIAL8E2 - 8 data bits, even parity, 2 stop bits SERIAL8O1 - 8 data bits, odd parity, 1 stop bit SERIAL8O2 - 8 data bits, odd parity, 2 stop bits SERIAL9N1 - 9 data bits, no parity, 1 stop bit SERIAL9N2 - 9 data bits, no parity, 2 stop bits SERIAL7O1 - 7 data bits, odd parity, 1 stop bit SERIAL7O2 - 7 data bits, odd parity, 1 stop bit SERIAL7E1 - 7 data bits, odd parity, 1 stop bit SERIAL7E2 - 7 data bits, odd parity, 1 stop bit LINMASTER13B - 8 data bits, no parity, 1 stop bit, LIN Master mode with 13-bit break generation LINSLAVE10B - 8 data bits, no parity, 1 stop bit, LIN Slave mode with 10-bit break detection LINSLAVE11B - 8 data bits, no parity, 1 stop bit, LIN Slave mode with 11-bit break detection Alternatively, configuration may be constructed manually by ORing ( ) the following configuration constants: SERIALDATABITS7 - 7 data bits SERIALDATABITS8 - 8 data bits SERIALDATABITS9 - 9 data bits SERIALSTOPBITS1 - 1 stop bit SERIALSTOPBITS2 - 2 stop bits SERIALSTOPBITS05 - 0.5 stop bits SERIALSTOPBITS15 - 1.5 stop bits SERIALPARITYNO - no parity SERIALPARITYEVEN - even parity SERIALPARITYODD - odd parity Hardware flow control, available only on Serial2 ( CTS - A7. RTS - RGBR ): SERIALFLOWCONTROLNONE - no flow control SERIALFLOWCONTROLRTS - RTS flow control SERIALFLOWCONTROLCTS - CTS flow control SERIALFLOWCONTROLRTSCTS - RTS/CTS flow control LINMODEMASTER - LIN Master LINMODESLAVE - LIN Slave LINBREAK13B - 13-bit break generation LINBREAK10B - 10-bit break detection LINBREAK11B - 10-bit break detection NOTE: LIN break detection may be enabled in both Master and Slave modes. velocidade. parameter that specifies the baud rate (long) config. parameter that specifies the number of data bits used, parity and stop bits (long) end() Available on Serial, Serial1, Serial2. Disables serial communication, allowing the RX and TX pins to be used for general input and output. To re-enable serial communication, call Serial1.begin() . available() Available on Serial, Serial1, Serial2. Get the number of bytes (characters) available for reading from the serial port. This is data thats already arrived and stored in the serial receive buffer (which holds 64 bytes). availableForWrite() Since 0.4.9. Available on Serial1, Serial2. Since 0.5.0. Available on USB Serial (Serial) Retrieves the number of bytes (characters) that can be written to this serial port without blocking. If blockOnOverrun(false) has been called, the method returns the number of bytes that can be written to the buffer without causing buffer overrun, which would cause old data to be discarded and overwritten. blockOnOverrun() Since 0.4.9. Available on Serial1, Serial2. Since 0.5.0. Available on USB Serial (Serial) Defines what should happen when calls to write()/print()/println()/printlnf() that would overrun the buffer. blockOnOverrun(true) - this is the default setting. When there is no room in the buffer for the data to be written, the program waits/blocks until there is room. This avoids buffer overrun, where data that has not yet been sent over serial is overwritten by new data. Use this option for increased data integrity at the cost of slowing down realtime code execution when lots of serial data is sent at once. blockOnOverrun(false) - when there is no room in the buffer for data to be written, the data is written anyway, causing the new data to replace the old data. This option is provided when performance is more important than data integrity. serialEvent() A family of application-defined functions that are called whenever there is data to be read from a serial peripheral. serialEvent: called when there is data available from Serial serialEvent1: called when there is data available from Serial1 serialEvent2: called when there is data available from Serial2 The serialEvent functions are called by the system as part of the application loop. Since these is an extension of the application loop, it is ok to call any functions at you would also call from loop(). peek() Available on Serial, Serial1, Serial2. Returns the next byte (character) of incoming serial data without removing it from the internal serial buffer. That is, successive calls to peek() will return the same character, as will the next call to read() . peek() returns the first byte of incoming serial data available (or -1 if no data is available) - int write() Available on Serial, Serial1, Serial2. Writes binary data to the serial port. This data is sent as a byte or series of bytes to send the characters representing the digits of a number use the print() function instead. Val. a value to send as a single byte str. a string to send as a series of bytes buf. an array to send as a series of bytes len. the length of the buffer write() will return the number of bytes written, though reading that number is optional. read() Available on Serial, Serial1, Serial2. Reads incoming serial data. read() returns the first byte of incoming serial data available (or -1 if no data is available) - int print() Available on Serial, Serial1, Serial2. Prints data to the serial port as human-readable ASCII text. This command can take many forms. Numbers are printed using an ASCII character for each digit. Floats are similarly printed as ASCII digits, defaulting to two decimal places. Bytes are sent as a single character. Characters and strings are sent as is. For example: Serial. print(78) gives 78 Serial. print(1.23456) gives 1.23 Serial. print(N) gives N Serial. print(Hello world.) gives Hello world. An optional second parameter specifies the base (format) to use permitted values are BIN (binary, or base 2), OCT (octal, or base 8), DEC (decimal, or base 10), HEX (hexadecimal, or base 16). For floating point numbers, this parameter specifies the number of decimal places to use. For example: Serial. print(78, BIN) gives 1001110 Serial. print(78, OCT) gives 116 Serial. print(78, DEC) gives 78 Serial. print(78, HEX) gives 4E Serial. println(1.23456, 0) gives 1 Serial. println(1.23456, 2) gives 1.23 Serial. println(1.23456, 4) gives 1.2346 println() Available on Serial, Serial1, Serial2. Prints data to the serial port as human-readable ASCII text followed by a carriage return character (ASCII 13, or r) and a newline character (ASCII 10, or n). This command takes the same forms as Serial. print() . Val. the value to print - any data type format. specifies the number base (for integral data types) or number of decimal places (for floating point types) println() returns the number of bytes written, though reading that number is optional - sizet (long) printf() Available on Serial, Serial1, Serial2. Provides printf - style formatting over serial. printf allows strings to be built by combining a number of values with text. Running this code prints: The last printf() call could be changed to printlnf() to avoid a separate call to println() . printlnf() Available on Serial, Serial1, Serial2. formatted output followed by a newline. Produces the same output as printf which is then followed by a newline character, so to that subsequent output appears on the next line. flush() Waits for the transmission of outgoing serial data to complete. flush() neither takes a parameter nor returns anything halfduplex() Available on Serial1, Serial2. Puts Serial1 into half-duplex mode. In this mode both the transmit and receive are on the TX pin. This mode can be used for a single wire bus communications scheme between microcontrollers. halfduplex() takes one argument: true enables half-duplex mode, false disables half-duplex mode halfduplex() returns nothing SPI This library allows you to communicate with SPI devices, with the Photon as the master device. Since 0.5.0 the Photon can function as a slave. The hardware SPI pin functions, which can be used via the SPI object, are mapped as follows: There is a second hardware SPI interface available, which can be used via the SPI1 object. This second port is mapped as follows: Note . Because there are multiple SPI peripherals available, be sure to use the same SPI. SPI1 object with all associated functions. I. e., begin() Initializes the SPI bus by setting SCK, MOSI, and a user-specified slave-select pin to outputs, MISO to input. SCK is pulled either high or low depending on the configured SPI data mode (default high for SPIMODE3 ). Slave-select is pulled high. Note: The SPI firmware ONLY initializes the user-specified slave-select pin as an OUTPUT. The users code must control the slave-select pin with digitalWrite() before and after each SPI transfer for the desired SPI slave device. Calling SPI. end() does NOT reset the pin mode of the SPI pins. Where, the parameter ss is the SPI device slave-select pin to initialize. If no pin is specified, the default pin is SS (A2). For SPI1. the default ss pin is SS (D5) . begin(SPIMode, uint16t) Initializes the Photon SPI peripheral in master or slave mode. Note: MISO, MOSI and SCK idle in high-impedance state when SPI peripheral is configured in slave mode and the device is not selected. mode. SPIMODEMASTER or SPIMODESLAVE sspin. slave-select pin to initialize. If no pin is specified, the default pin is SS (A2). For SPI1. the default pin is SS (D5) . end() Disables the SPI bus (leaving pin modes unchanged). setBitOrder() Sets the order of the bits shifted out of and into the SPI bus, either LSBFIRST (least-significant bit first) or MSBFIRST (most-significant bit first). Where, the parameter order can either be LSBFIRST or MSBFIRST . setClockSpeed Sets the SPI clock speed. The value can be specified as a direct value, or as as a value plus a multiplier. The clock speed cannot be set to any arbitrary value, but is set internally by using a divider (see SPI. setClockDivider() ) that gives the highest clock speed not greater than the one specified. This method can make writing portable code easier, since it specifies the clock speed absolutely, giving comparable results across devices. In contrast, specifying the clock speed using dividers is typically not portable since is dependent upon the system clock speed. setClockDividerReference This function aims to ease porting code from other platforms by setting the clock speed that SPI. setClockDivider is relative to. For example, when porting an Arduino SPI library, each to SPI. setClockDivider() would need to be changed to reflect the system clock speed of the device being used. This can be avoided by placing a call to SPI. setClockDividerReference() before the other SPI calls. The default clock divider reference is the system clock. On the Photon and Electron, the system clock speeds are: setClockDivider() Sets the SPI clock divider relative to the selected clock reference. The available dividers are 2, 4, 8, 16, 32, 64, 128 or 256. The default setting is SPICLOCKDIV4, which sets the SPI clock to one-quarter the frequency of the system clock. Where the parameter, divider can be: SPICLOCKDIV2 SPICLOCKDIV4 SPICLOCKDIV8 SPICLOCKDIV16 SPICLOCKDIV32 SPICLOCKDIV64 SPICLOCKDIV128 SPICLOCKDIV256 setDataMode() Sets the SPI data mode: that is, clock polarity and phase. See the Wikipedia article on SPI for details. Where the parameter, mode can be: transfer() Transfers one byte over the SPI bus, both sending and receiving. Where the parameter val. can is the byte to send out over the SPI bus. transfer(void, void, sizet, std::function) For transferring a large number of bytes, this form of transfer() uses DMA to speed up SPI data transfer and at the same time allows you to run code in parallel to the data transmission. The function initialises, configures and enables the DMA peripherals channel and stream for the selected SPI peripheral for both outgoing and incoming data and initiates the data transfer. If a user callback function is passed then it will be called after completion of the DMA transfer. This results in asynchronous filling of RX buffer after which the DMA transfer is disabled till the transfer function is called again. If NULL is passed as a callback then the result is synchronous i. e. the function will only return once the DMA transfer is complete. Nota . The SPI protocol is based on a one byte OUT / one byte IN inteface. For every byte expected to be received, one (dummy, typically 0x00 or 0xFF) byte must be sent. txbuffer. array of Tx bytes that is filled by the user before starting the SPI transfer. If NULL. default dummy 0xFF bytes will be clocked out. rxbuffer. array of Rx bytes that will be filled by the slave during the SPI transfer. If NULL. the received data will be discarded. length. number of data bytes that are to be transferred myFunction. user specified function callback to be called after completion of the SPI DMA transfer NOTE: txbuffer and rxbuffer sizes MUST be identical (of size length ) Since 0.5.0 When SPI peripheral is configured in slave mode, the transfer will be canceled when the master deselects this slave device. The user application can check the actual number of bytes received/transmitted by calling available() . transferCancel() Aborts the configured DMA transfer and disables the DMA peripherals channel and stream for the selected SPI peripheral for both outgoing and incoming data. Nota . The user specified SPI DMA transfer completion function will still be called to indicate the end of DMA transfer. The user application can check the actual number of bytes received/transmitted by calling available() . onSelect() Registers a function to be called when the SPI master selects or deselects this slave device by pulling configured slave-select pin low (selected) or high (deselected). Parameters: handler. the function to be called when the slave is selected or deselected this should take a single uint8t parameter (the current state: 1 - selected, 0 - deselected) and return nothing, e. g. void myHandler(uint8t state) available() Returns the number of bytes available for reading in the rxbuffer supplied in transfer(). In general, returns the actual number of bytes received/transmitted during the ongoing or finished DMA transfer. Returns the number of bytes available. Wire (I2C) This library allows you to communicate with I2C / TWI(Two Wire Interface) devices. On the Core/Photon/Electron, D0 is the Serial Data Line (SDA) and D1 is the Serial Clock (SCL). Both SCL and SDA pins are open-drain outputs that only pull LOW and typically operate with 3.3V logic, but are tolerant to 5V. Connect a pull-up resistor(1.5k to 10k) on the SDA line to 3V3. Connect a pull-up resistor(1.5k to 10k) on the SCL line to 3V3. If you are using a breakout board with an I2C peripheral, check to see if it already incorporates pull-up resistors. These pins are used via the Wire object. setSpeed() Sets the I2C clock speed. This is an optional call (not from the original Arduino specs.) and must be called once before calling begin(). The default I2C clock speed is 100KHz and the maximum clock speed is 400KHz. clockSpeed. CLOCKSPEED100KHZ, CLOCKSPEED400KHZ or a user specified speed in hertz (e. g. Wire. setSpeed(20000) for 20kHz) stretchClock() Enables or Disables I2C clock stretching. This is an optional call (not from the original Arduino specs.) and must be called once before calling begin(). I2C clock stretching is only used with I2C Slave mode. The default I2C clock stretching mode is enabled. stretch. boolean. true will enable clock stretching (default). false will disable clock stretching. begin() Initiate the Wire library and join the I2C bus as a master or slave. This should normally be called only once. Parameters: address. the 7-bit slave address (optional) if not specified, join the bus as an I2C master. If address is specified, join the bus as an I2C slave. end() Releases the I2C bus so that the pins used by the I2C bus are available for general purpose I/O. isEnabled() Used to check if the Wire library is enabled already. Useful if using multiple slave devices on the same I2C bus. Check if enabled before calling Wire. begin() again. Returns: boolean true if I2C enabled, false if I2C disabled. requestFrom() Used by the master to request bytes from a slave device. The bytes may then be retrieved with the available() and read() functions. endereço. the 7-bit address of the device to request bytes from quantity. the number of bytes to request (Max. 32) stop. boolean. true will send a stop message after the request, releasing the bus. false will continually send a restart after the request, keeping the connection active. The bus will not be released, which prevents another master device from transmitting between messages. This allows one master device to send multiple transmissions while in control. If no argument is specified, the default value is true . Returns: byte. the number of bytes returned from the slave device. If a timeout occurs, will return 0 . reset() Attempts to reset the I2C bus. This should be called only if the I2C bus has has hung. In 0.4.6 additional rework was done for the I2C bus on the Photon and Electron, so we hope this function isnt required, and its provided for completeness. beginTransmission() Begin a transmission to the I2C slave device with the given address. Subsequently, queue bytes for transmission with the write() function and transmit them by calling endTransmission() . Parameters: address. the 7-bit address of the device to transmit to. endTransmission() Ends a transmission to a slave device that was begun by beginTransmission() and transmits the bytes that were queued by write() . Parameters: stop. boolean. true will send a stop message after the last byte, releasing the bus after transmission. false will send a restart, keeping the connection active. The bus will not be released, which prevents another master device from transmitting between messages. This allows one master device to send multiple transmissions while in control. If no argument is specified, the default value is true . Returns: byte. which indicates the status of the transmission: 0: success 1: busy timeout upon entering endTransmission() 2: START bit generation timeout 3: end of address transmission timeout 4: data byte transfer timeout 5: data byte transfer succeeded, busy timeout immediately after write() Writes data from a slave device in response to a request from a master, or queues bytes for transmission from a master to slave device (in-between calls to beginTransmission() and endTransmission() ). Buffer size is truncated to 32 bytes writing bytes beyond 32 before calling endTransmission() will be ignored. valor. a value to send as a single byte string. a string to send as a series of bytes data. an array of data to send as bytes length. the number of bytes to transmit (Max. 32) write() will return the number of bytes written, though reading that number is optional. available() Returns the number of bytes available for retrieval with read(). This should be called on a master device after a call to requestFrom() or on a slave inside the onReceive() handler. Returns: The number of bytes available for reading. read() Reads a byte that was transmitted from a slave device to a master after a call to requestFrom() or was transmitted from a master to a slave. read() inherits from the Stream utility class. Returns: The next byte received peek() Similar in use to read(). Reads (but does not remove from the buffer) a byte that was transmitted from a slave device to a master after a call to requestFrom() or was transmitted from a master to a slave. read() inherits from the Stream utility class. Useful for peeking at the next byte to be read. Returns: The next byte received (without removing it from the buffer) onReceive() Registers a function to be called when a slave device receives a transmission from a master. Parameters: handler. the function to be called when the slave receives data this should take a single int parameter (the number of bytes read from the master) and return nothing, e. g. void myHandler(int numBytes) onRequest() Register a function to be called when a master requests data from this slave device. Parameters: handler. the function to be called, takes no parameters and returns nothing, e. g. void myHandler() CAN (CANbus) Controller area network (CAN bus) is a bus used in most automobiles, as well as some industrial equipment, for communication between different microcontrollers. The Photon and Electron support communicating with CAN devices via the CAN bus. The Photon and Electron have a CANbus on pins D1 (CAN2TX) and D2 (CAN2RX). The Electron only, has a second CANbus on pins C4 (CAN1TX) and C5 (CAN1TX). Nota . an additional CAN transceiver integrated circuit is needed to convert the logic-level voltages of the Photon or Electron to the voltage levels of the CAN bus. On the Photon or Electron, connect pin D1 to the TX pin of the CAN transceiver and pin D2 to the RX pin. On the Electron only, connect pin C4 to the TX pin of the CAN transceiver and pin C5 to the RX pin. CANMessage The CAN message struct has these members: CANChannel Create a CANChannel global object to connect to a CAN bus on the specified pins. pins. the Photon and Electron support pins CAND1D2. and the Electron only, supports pins CANC4C5 rxQueueSize (optional): the receive queue size (default 32 message) txQueueSize (optional): the transmit queue size (default 32 message) begin() Joins the bus at the given baud rate. baud. common baud rates are 50000, 100000, 125000, 250000, 500000, 1000000 flags (optional): CANTESTMODE to run the CAN bus in test mode where every transmitted message will be received back end() Disconnect from the bus. available() The number of received messages waiting in the receive queue. Returns: uint8t. the number of messages. receive() Take a received message from the receive queue. This function does not wait for a message to arrive. mensagem. where the received message will be copied Returns: boolean true if a message was received, false if the receive queue was empty. transmit() Add a message to the queue to be transmitted to the CAN bus as soon as possible. mensagem. the message to be transmitted Returns: boolean true if the message was added to the queue, false if the transmit queue was full. Nota . Since the CAN bus requires at least one other CAN node to acknowledge transmitted messages if the Photon or Electron is alone on the bus (such as when using a CAN shield with no other CAN node connected) then messages will never be transmitted and the transmit queue will fill up. addFilter() Filter which messages will be added to the receive queue. By default all messages are received. When filters are added, only messages matching the filters will be received. Others will be discarded. id. the id pattern to match mask. the mask pattern to match type (optional): CANFILTERSTANDARD (default) or CANFILTEREXTENDED Returns: boolean true if the filter was added, false if there are too many filters (14 filters max). clearFilters() Clear filters and accept all messages. isEnabled() Used to check if the CAN bus is enabled already. Check if enabled before calling can. begin() again. Returns: boolean true if the CAN bus is enabled, false if the CAN bus is disabled. errorStatus() Get the current error status of the CAN bus. Returns: int CANNOERROR when everything is ok, CANERRORPASSIVE when not attempting to transmit messages but still acknowledging messages, CANBUSOFF when not transmitting or acknowledging messages. This value is only updated when attempting to transmit messages. The two most common causes of error are: being alone on the bus (such as when using a CAN shield not connected to anything) or using the wrong baud rate. Attempting to transmit in those situations will result in CANBUSOFF . Errors heal automatically when properly communicating with other microcontrollers on the CAN bus. IPAddress Creates an IP address that can be used with TCPServer, TCPClient, and UDP objects. The IPAddress also allows for comparisons. You can also use indexing the get or change individual bytes in the IP address. You can also assign to an IPAddress from an array of uint8s or a 32-bit unsigned integer. Finally IPAddress can be used directly with print. TCPServer Create a server that listens for incoming connections on the specified port. Parameters: port. the port to listen on ( int ) begin() Tells the server to begin listening for incoming connections. available() Gets a client that is connected to the server and has data available for reading. The connection persists when the returned client object goes out of scope you can close it by calling client. stop() . available() inherits from the Stream utility class. write() Write data to the last client that connected to a server. This data is sent as a byte or series of bytes. Val. a value to send as a single byte (byte or char) buf. an array to send as a series of bytes (byte or char) len. the length of the buffer Returns: byte. write() returns the number of bytes written. It is not necessary to read this. print() Print data to the last client connected to a server. Prints numbers as a sequence of digits, each an ASCII character (e. g. the number 123 is sent as the three characters 1, 2, 3). dados. the data to print (char, byte, int, long, or string) BASE (optional): the base in which to print numbers: BIN for binary (base 2), DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16). Returns: byte. print() will return the number of bytes written, though reading that number is optional println() Print data, followed by a newline, to the last client connected to a server. Prints numbers as a sequence of digits, each an ASCII character (e. g. the number 123 is sent as the three characters 1, 2, 3). data (optional): the data to print (char, byte, int, long, or string) BASE (optional): the base in which to print numbers: BIN for binary (base 2), DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16). TCPClient Creates a client which can connect to a specified internet IP address and port (defined in the client. connect() function). connected() Whether or not the client is connected. Note that a client is considered connected if the connection has been closed but there is still unread data. Returns true if the client is connected, false if not. connect() Connects to a specified IP address and port. The return value indicates success or failure. Also supports DNS lookups when using a domain name. ip. the IP address that the client will connect to (array of 4 bytes) hostname. the host name the client will connect to (string, ex.:particle. io) port. the port that the client will connect to ( int ) Returns true if the connection succeeds, false if not. write() Write data to the server the client is connected to. This data is sent as a byte or series of bytes. Val. a value to send as a single byte (byte or char) buf. an array to send as a series of bytes (byte or char) len. the length of the buffer Returns: byte. write() returns the number of bytes written. It is not necessary to read this value. print() Print data to the server that a client is connected to. Prints numbers as a sequence of digits, each an ASCII character (e. g. the number 123 is sent as the three characters 1, 2, 3). dados. the data to print (char, byte, int, long, or string) BASE (optional): the base in which to print numbers: BIN for binary (base 2), DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16). Returns: byte. print() will return the number of bytes written, though reading that number is optional println() Print data, followed by a carriage return and newline, to the server a client is connected to. Prints numbers as a sequence of digits, each an ASCII character (e. g. the number 123 is sent as the three characters 1, 2, 3). data (optional): the data to print (char, byte, int, long, or string) BASE (optional): the base in which to print numbers: BIN for binary (base 2), DEC for decimal (base 10), OCT for octal (base 8), HEX for hexadecimal (base 16). available() Returns the number of bytes available for reading (that is, the amount of data that has been written to the client by the server it is connected to). Returns the number of bytes available. read() Read the next byte received from the server the client is connected to (after the last call to read() ). Returns the next byte (or character), or -1 if none is available. or int read(uint8t buffer, sizet size) reads all readily available bytes up to size from the server the client is connected to into the provided buffer . Returns the number of bytes (or characters) read into buffer . flush() Waits until all outgoing data in buffer has been sent. NOTE: That this function does nothing at present. remoteIP() Retrieves the remote IPAddress of a connected TCPClient. When the TCPClient is retrieved from TCPServer. available() (where the client is a remote client connecting to a local server) the IPAddress gives the remote address of the connecting client. When TCPClient was created directly via TCPClient. connect(). then remoteIP returns the remote server the client is connected to. stop() Disconnect from the server. UDP This class enables UDP messages to be sent and received. Note that UDP does not guarantee that messages are always delivered, or that they are delivered in the order supplied. In cases where your application requires a reliable connection, TCPClient is a simpler alternative. There are two primary ways of working with UDP - buffered operation and unbuffered operation. buffered operation allows you to read and write packets in small pieces, since the system takes care of allocating the required buffer to hold the entire packet. to read a buffered packet, call parsePacket. then use available and read to retrieve the packet received to write a buffered packet, optionally call setBuffer to set the maximum size of the packet (the default is 512 bytes), followed by beginPacket. then as many calls to write / print as necessary to build the packet contents, followed finally by end to send the packet over the network. unbuffered operation allows you to read and write entire packets in a single operation - your application is responsible for allocating the buffer to contain the packet to be sent or received over the network. to read an unbuffered packet, call receivePacket with a buffer to hold the received packet. to write an unbuffered packet, call sendPacket with the packet buffer to send, and the destination address. begin() Initializes the UDP library and network settings. available() Get the number of bytes (characters) available for reading from the buffer. This is data thats already arrived. This function can only be successfully called after UDP. parsePacket() . available() inherits from the Stream utility class. Returns the number of bytes available to read. beginPacket() Starts a connection to write UDP data to the remote connection. remoteIP. the IP address of the remote connection (4 bytes) remotePort. the port of the remote connection (int) It returns nothing. endPacket() Called after writing buffered UDP data using write() or print(). The buffered data is then sent to the remote UDP peer. write() Writes UDP data to the buffer - no data is actually sent. Must be wrapped between beginPacket() and endPacket(). beginPacket() initializes the packet of data, it is not sent until endPacket() is called. mensagem. the outgoing message (char) buffer. an array to send as a series of bytes (byte or char) size. the length of the buffer byte. returns the number of characters sent. This does not have to be read parsePacket() Checks for the presence of a UDP packet, and reports the size. parsePacket() must be called before reading the buffer with UDP. read() . int. the size of a received UDP packet read() Reads UDP data from the specified buffer. If no arguments are given, it will return the next character in the buffer. This function can only be successfully called after UDP. parsePacket() . packetBuffer. buffer to hold incoming packets (char) MaxSize. maximum size of the buffer (int) int. returns the character in the buffer or -1 if no character is available flush() Waits until all outgoing data in buffer has been sent. NOTE: That this function does nothing at present. stop() Disconnect from the server. Release any resource being used during the UDP session. remoteIP() Returns the IP address of sender of the packet parsed by Udp. parsePacket() / Udp. receivePacket() . IPAddress. the IP address of the sender of the packet parsed by Udp. parsePacket() / Udp. receivePacket() . remotePort() Returns the port from which the UDP packet was sent. The packet is the one most recently processed by Udp. parsePacket() / Udp. receivePacket() . int. the port from which the packet parsed by Udp. parsePacket() / Udp. receivePacket() was sent. setBuffer() Initializes the buffer used by a UDP instance for buffered reads/writes. The buffer is used when your application calls beginPacket() and parsePacket(). If setBuffer() isnt called, the buffer size defaults to 512 bytes, and is allocated when buffered operation is initialized via beginPacket() or parsePacket() . unsigned int. the size of the buffer pointer. the buffer. If not provided, or NULL the system will attempt to allocate a buffer of the size requested. true when the buffer was successfully allocated, false if there was insufficient memory. (For application-provided buffers the function always returns true .) releaseBuffer() Releases the buffer previously set by a call to setBuffer() . This is typically required only when performing advanced memory management and the UDP instance is not scoped to the lifetime of the application. sendPacket() Sends a packet, unbuffered, to a remote UDP peer. pointer (buffer): the buffer of data to send int (bufferSize): the number of bytes of data to send IPAddress (remoteIP): the destination address of the remote peer int (remotePort): the destination port of the remote peer int. The number of bytes written. Negative value on error. joinMulticast() Join a multicast address for all UDP sockets which are on the same network interface as this one. This will allow reception of multicast packets sent to the given address for UDP sockets which have bound the port to which the multicast packet was sent. Must be called only after begin() so that the network interface is established. leaveMulticast() Leaves a multicast group previously joined on a specific multicast address. Servo This library allows your device to control RC (hobby) servo motors. Servos have integrated gears and a shaft that can be precisely controlled. Standard servos allow the shaft to be positioned at various angles, usually between 0 and 180 degrees. Continuous rotation servos allow the rotation of the shaft to be set to various speeds. NOTE: Unlike Arduino, you do not need to include Servo. h it is included automatically. attach() Set up a servo on a particular pin. Note that, Servo can only be attached to pins with a timer. on the Core, Servo can be connected to A0, A1, A4, A5, A6, A7, D0, and D1. on the Photon, Servo can be connected to A4, A5, WKP, RX, TX, D0, D1, D2, D3 write() Writes a value to the servo, controlling the shaft accordingly. On a standard servo, this will set the angle of the shaft (in degrees), moving the shaft to that orientation. On a continuous rotation servo, this will set the speed of the servo (with 0 being full-speed in one direction, 180 being full speed in the other, and a value near 90 being no movement). writeMicroseconds() Writes a value in microseconds (uS) to the servo, controlling the shaft accordingly. On a standard servo, this will set the angle of the shaft. On standard servos a parameter value of 1000 is fully counter-clockwise, 2000 is fully clockwise, and 1500 is in the middle. Note that some manufactures do not follow this standard very closely so that servos often respond to values between 700 and 2300. Feel free to increase these endpoints until the servo no longer continues to increase its range. Note however that attempting to drive a servo past its endpoints (often indicated by a growling sound) is a high-current state, and should be avoided. Continuous-rotation servos will respond to the writeMicrosecond function in an analogous manner to the write function. read() Read the current angle of the servo (the value passed to the last call to write()). Returns an integer from 0 to 180 degrees. attached() Check whether the Servo variable is attached to a pin. Returns a boolean. detach() Detach the Servo variable from its pin. setTrim() Sets a trim value that allows minute timing adjustments to correctly calibrate 90 as the stationary point. RGB This library allows the user to control the RGB LED on the front of the device. control(usercontrol) User can take control of the RGB LED, or give control back to the system. controlled() Returns Boolean true when the RGB LED is under user control, or false when it is not. color(red, green, blue) Set the color of the RGB with three values, 0 to 255 (0 is off, 255 is maximum brightness for that color). User must take control of the RGB LED before calling this method. brightness(val) Scale the brightness value of all three RGB colors with one value, 0 to 255 (0 is 0, 255 is 100). This setting persists after RGB. control() is set to false. and will govern the overall brightness of the RGB LED under normal system operation. User must take control of the RGB LED before calling this method. onChange(handler) Specifies a function to call when the color of the RGB LED changes. It can be used to implement an external RGB LED. onChange can also call a method on an object. Time The device synchronizes time with the Particle Cloud during the handshake. From then, the time is continually updated on the device. This reduces the need for external libraries to manage dates and times. hour() Retrieve the hour for the current or given time. Integer is returned without a leading zero. Optional parameters: Integer (Unix timestamp) Returns: Integer 0-23 hourFormat12() Retrieve the hour in 12-hour format for the current or given time. Integer is returned without a leading zero. Optional parameters: Integer (Unix timestamp) Returns: Integer 1-12 isAM() Returns true if the current or given time is AM. Optional parameters: Integer (Unix timestamp) Returns: Unsigned 8-bit integer: 0 false, 1 true isPM() Returns true if the current or given time is PM. Optional parameters: Integer (Unix timestamp) Returns: Unsigned 8-bit integer: 0 false, 1 true minute() Retrieve the minute for the current or given time. Integer is returned without a leading zero. Optional parameters: Integer (Unix timestamp) Returns: Integer 0-59 second() Retrieve the seconds for the current or given time. Integer is returned without a leading zero. Optional parameters: Integer (Unix timestamp) Returns: Integer 0-59 day() Retrieve the day for the current or given time. Integer is returned without a leading zero. Optional parameters: Integer (Unix timestamp) Returns: Integer 1-31 weekday() Retrieve the weekday for the current or given time. Optional parameters: Integer (Unix timestamp) Returns: Integer 1-7 month() Retrieve the month for the current or given time. Integer is returned without a leading zero. Optional parameters: Integer (Unix timestamp) Returns: Integer 1-12 year() Retrieve the 4-digit year for the current or given time. Optional parameters: Integer (Unix timestamp) now() Retrieve the current time as seconds since January 1, 1970 (commonly known as Unix time or epoch time). This time is not affected by the timezone setting. local() Retrieve the current time in the configured timezone as seconds since January 1, 1970 (commonly known as Unix time or epoch time). This time is affected by the timezone setting. Note that the functions in the Time class expect times in UTC time, so the result from this should be used carefully. Local time is also affected by the Daylight Saving Time (DST) settings. zone() Set the time zone offset (/-) from UTC. The device will remember this offset until reboot. NOTA . This function does not observe daylight savings time. Parameters: floating point offset from UTC in hours, from -12.0 to 14.0 isDST() Returns true if Daylight Saving Time (DST) is in effect. Returns: Unsigned 8-bit integer: 0 false, 1 true getDSTOffset() Retrieve the current Daylight Saving Time (DST) offset that is added to the current local time when Time. beginDST() has been called. The default is 1 hour. Returns: floating point DST offset in hours (default is 1.0 hours) setDSTOffset() Set a custom Daylight Saving Time (DST) offset. The device will remember this offset until reboot. Parameters: floating point offset in hours, from 0.0 to 2.0 beginDST() Start applying Daylight Saving Time (DST) offset to the current time. endDST() Stop applying Daylight Saving Time (DST) offset to the current time. setTime() Set the system time to the given timestamp. NOTA . This will override the time set by the Particle Cloud. If the cloud connection drops, the reconnection handshake will set the time again Parameters: Unix timestamp (integer) timeStr() Return string representation for the given time. NB: In 0.3.4 and earlier, this function included a newline at the end of the returned string. This has been removed in 0.4.0. format() Formats a time string using a configurable format. The formats available are: TIMEFORMATDEFAULT TIMEFORMATISO8601FULL custom format based on strftime() setFormat() Sets the format string that is the default value used by format() . In more advanced cases, you can set the format to a static string that follows the same syntax as the strftime() function. getFormat() Retrieves the currently configured format string for time formatting with format() . millis() Returns the number of milliseconds since the device began running the current program. This number will overflow (go back to zero), after approximately 49 days. unsigned long time millis() Note: The return value for millis is an unsigned long, errors may be generated if a programmer tries to do math with other datatypes such as ints. micros() Returns the number of microseconds since the device began running the current program. Firmware v0.4.3 and earlier: This number will overflow (go back to zero), after exactly 59,652,323 microseconds (0. 59,652,322) on the Core and after exactly 35,791,394 microseconds (0. 35,791,394) on the Photon and Electron. unsigned long time micros() delay() Pauses the program for the amount of time (in miliseconds) specified as parameter. (There are 1000 milliseconds in a second.) ms is the number of milliseconds to pause (unsigned long) NOTE: the parameter for millis is an unsigned long, errors may be generated if a programmer tries to do math with other datatypes such as ints. delayMicroseconds() Pauses the program for the amount of time (in microseconds) specified as parameter. There are a thousand microseconds in a millisecond, and a million microseconds in a second. us is the number of microseconds to pause (unsigned int) Interrupts Interrupts are a way to write code that is run when an external event occurs. As a general rule, interrupt code should be very fast, and non-blocking. This means performing transfers, such as I2C, Serial, TCP should not be done as part of the interrupt handler. Rather, the interrupt handler can set a variable which instructs the main loop that the event has occurred. attachInterrupt() Specifies a function to call when an external interrupt occurs. Replaces any previous function that was attached to the interrupt. NOTE: pinMode() MUST be called prior to calling attachInterrupt() to set the desired mode for the interrupt pin (INPUT, INPUTPULLUP or INPUTPULLDOWN). External interrupts are supported on the following pins: Core: D0, D1, D2, D3, D4, A0, A1, A3, A4, A5, A6, A7 Photon: All pins with the exception of D0 and A5 (since at present Mode Button external interrupt(EXTI) line is shared with D0, A5). Also please note following are the pins for which EXTI lines are shared so only one can work at a time: D1, A4 D2, A0, A3 D3, DAC D4, A1 pin. the pin number function. the function to call when the interrupt occurs this function must take no parameters and return nothing. This function is sometimes referred to as an interrupt service routine (ISR). mode. defines when the interrupt should be triggered. Three constants are predefined as valid values: CHANGE to trigger the interrupt whenever the pin changes value, RISING to trigger when the pin goes from low to high, FALLING for when the pin goes from high to low. priority (optional): the priority of this interrupt. Default priority is 13. Lower values increase the priority of the interrupt. subpriority (optional): the subpriority of this interrupt. Default subpriority is 0. The function returns a boolean whether the ISR was successfully attached (true) or not (false). You can attach a method in a C object as an interrupt handler. Using Interrupts: Interrupts are useful for making things happen automatically in microcontroller programs, and can help solve timing problems. Good tasks for using an interrupt may include reading a rotary encoder, or monitoring user input. If you wanted to insure that a program always caught the pulses from a rotary encoder, so that it never misses a pulse, it would make it very tricky to write a program to do anything else, because the program would need to constantly poll the sensor lines for the encoder, in order to catch pulses when they occurred. Other sensors have a similar interface dynamic too, such as trying to read a sound sensor that is trying to catch a click, or an infrared slot sensor (photo-interrupter) trying to catch a coin drop. In all of these situations, using an interrupt can free the microcontroller to get some other work done while not missing the input. About Interrupt Service Routines: ISRs are special kinds of functions that have some unique limitations most other functions do not have. An ISR cannot have any parameters, and they shouldnt return anything. Generally, an ISR should be as short and fast as possible. If your sketch uses multiple ISRs, only one can run at a time, other interrupts will be executed after the current one finishes in an order that depends on the priority they have. millis() relies on interrupts to count, so it will never increment inside an ISR. Since delay() requires interrupts to work, it will not work if called inside an ISR. Using delayMicroseconds() will work as normal. Typically global variables are used to pass data between an ISR and the main program. To make sure variables shared between an ISR and the main program are updated correctly, declare them as volatile . detachInterrupt() Turns off the given interrupt. pin is the pin number of the interrupt to disable. interrupts() Re-enables interrupts (after theyve been disabled by noInterrupts() ). Interrupts allow certain important tasks to happen in the background and are enabled by default. Some functions will not work while interrupts are disabled, and incoming communication may be ignored. Interrupts can slightly disrupt the timing of code, however, and may be disabled for particularly critical sections of code. interrupts() neither accepts a parameter nor returns anything. noInterrupts() Disables interrupts (you can re-enable them with interrupts() ). Interrupts allow certain important tasks to happen in the background and are enabled by default. Some functions will not work while interrupts are disabled, and incoming communication may be ignored. Interrupts can slightly disrupt the timing of code, however, and may be disabled for particularly critical sections of code. noInterrupts() neither accepts a parameter nor returns anything. Software Timers Since 0.4.7. This feature is available on the Photon, P1 and Electron out the box. On the Core, the freertos4core library should be used to add FreeRTOS to the core. Software Timers provide a way to have timed actions in your program. FreeRTOS provides the ability to have up to 10 Software Timers at a time with a minimum resolution of 1 millisecond. It is common to use millis() based timers though exact timing is not always possible (due to other program delays). Software timers are maintained by FreeRTOS and provide a more reliable method for running timed actions using callback functions. Please note that Software Timers are chained and will be serviced sequencially when several timers trigger simultaneously, thus requiring special consideration when writing callback functions. Timers may be started, stopped, reset within a user program or an ISR. They may also be disposed, removing them from the (max. 10) active timer list. The timer callback is similar to an interrupt - it shouldnt block. However, it is less restrictive than an interrupt. If the code does block, the system will not crash - the only consequence is that other software timers that should have triggered will be delayed until the blocking timer callback function returns. Timer timer(period, callback, oneshot) period is the period of the timer in milliseconds (unsigned int) callback is the callback function which gets called when the timer expires. oneshot (optional, since 0.4.9) when true. the timer is fired once and then stopped automatically. The default is false - a repeating timer. Class member callbacks A class member function can be used as a callback using this syntax to create the timer: Timer timer(period, callback, instance, oneshot) period is the period of the timer in milliseconds (unsigned int) callback is the class member function which gets called when the timer expires. instance the instance of the class to call the callback function on. oneshot (optional, since 0.4.9) when true. the timer is fired once and then stopped automatically. The default is false - a repeating timer. start() Starts a stopped timer (a newly created timer is stopped). If start() is called for a running timer, it will be reset. stop() Stops a running timer. changePeriod() Changes the period of a previously created timer. It can be called to change the period of an running or stopped timer. newPeriod is the new timer period (unsigned int) reset() Resets a timer. If a timer is running, it will reset to zero. If a timer is stopped, it will be started. startFromISR() stopFromISR() resetFromISR() changePeriodFromISR() startFromISR() stopFromISR() resetFromISR() changePeriodFromISR() Start, stop and reset a timer or change a timers period (as above) BUT from within an ISR. These functions MUST be called when doing timer operations within an ISR. dispose() Stop and remove a timer from the (max. 10) timer list, freeing a timer slot in the list. isActive() Returns true if the timer is in active state (pending), or false otherwise. Application Watchdog The Application Watchdog is a software-implemented watchdog using a critical-priority thread that wakes up at a given timeout interval to see if the application has checked in. If the application has not exited loop, or called Particle. process() within the given timeout, or called ApplicationWatchdog. checkin(). the watchdog calls the given timeout function, which is typically System. reset. This could also be a user defined function that takes care of critical tasks before finally calling System. reset . A default stacksize of 512 is used for the thread. stacksize is an optional parameter. The stack can be made larger or smaller as needed. This is the amount of memory needed to support the thread and function that is called. In practice, on the Photon (v0.5.0) calling the System. reset function requires approx. 170 bytes of memory. If not enough memory is allocated, the application will crash due to a Stack Overflow. The RGB LED will flash a red SOS pattern, followed by 13 blinks . The application watchdog requires interrupts to be active in order to function. Enabling the hardware watchdog in combination with this is recommended, so that the system resets in the event that interrupts are not firing. Math Note that in addition to functions outlined below all of the newlib math functions described at sourceware. org are also available for use by simply including the math. h header file thus: min() Calculates the minimum of two numbers. x is the first number, any data type y is the second number, any data type The functions returns the smaller of the two numbers. NOTE: Perhaps counter-intuitively, max() is often used to constrain the lower end of a variables range, while min() is used to constrain the upper end of the range. WARNING: Because of the way the min() function is implemented, avoid using other functions inside the brackets, it may lead to incorrect results max() Calculates the maximum of two numbers. x is the first number, any data type y is the second number, any data type The functions returns the larger of the two numbers. NOTE: Perhaps counter-intuitively, max() is often used to constrain the lower end of a variables range, while min() is used to constrain the upper end of the range. WARNING: Because of the way the max() function is implemented, avoid using other functions inside the brackets, it may lead to incorrect results abs() Computes the absolute value of a number. where x is the number The function returns x if x is greater than or equal to 0 and returns - x if x is less than 0 . WARNING: Because of the way the abs() function is implemented, avoid using other functions inside the brackets, it may lead to incorrect results. constrain() Constrains a number to be within a range. x is the number to constrain, all data types a is the lower end of the range, all data types b is the upper end of the range, all data types The function will return: x. if x is between a and b a. if x is less than a b. if x is greater than b map() Re-maps a number from one range to another. That is, a value of fromLow would get mapped to toLow. a value of fromHigh to toHigh. values in-between to values in-between, etc. map(value, fromLow, fromHigh, toLow, toHigh) Does not constrain values to within the range, because out-of-range values are sometimes intended and useful. The constrain() function may be used either before or after this function, if limits to the ranges are desired. Note that the lower bounds of either range may be larger or smaller than the upper bounds so the map() function may be used to reverse a range of numbers, for example y map(x, 1, 50, 50, 1) The function also handles negative numbers well, so that this example y map(x, 1, 50, 50, -100) is also valid and works well. The map() function uses integer math so will not generate fractions, when the math might indicate that it should do so. Fractional remainders are truncated, and are not rounded or averaged. valor. the number to map fromLow. the lower bound of the values current range fromHigh. the upper bound of the values current range toLow. the lower bound of the values target range toHigh. the upper bound of the values target range The function returns the mapped value Appendix: For the mathematically inclined, heres the whole function pow() Calculates the value of a number raised to a power. pow() can be used to raise a number to a fractional power. This is useful for generating exponential mapping of values or curves. base is the number (float) exponent is the power to which the base is raised (float) The function returns the result of the exponentiation (double) sqrt() Calculates the square root of a number. x is the number, any data type The function returns the numbers square root (double) Random Numbers The firmware incorporates a pseudo-random number generator. random() Retrieves the next random value, restricted to a given range. max - the upper limit of the random number to retrieve. Returns: a random value between 0 and up to, but not including max . NB: When max is 0, the result is always 0. min - the lower limit (inclusive) of the random number to retrieve. max - the upper limit (exclusive) of the random number to retrieve. Returns: a random value from min and up to, but not including max . NB: If min is greater or equal to max. the result is always 0. randomSeed() newSeed - the new random seed The pseudorandom numbers produced by the firmware are derived from a single value - the random seed. The value of this seed fully determines the sequence of random numbers produced by successive calls to random(). Using the same seed on two separate runs will produce the same sequence of random numbers, and in contrast, using different seeds will produce a different sequence of random numbers. On startup, the default random seed is set by the system to 1. Unless the seed is modified, the same sequence of random numbers would be produced each time the system starts. Fortunately, when the device connects to the cloud, it receives a very randomized seed value, which is used as the random seed. So you can be sure the random numbers produced will be different each time your program is run. Disable random seed from the cloud When the device receives a new random seed from the cloud, its passed to this function: The system implementation of this function calls randomSeed() to set the new seed value. If you dont wish to use random seed values from the cloud, you can take control of the random seeds set by adding this code to your app: In the example, the seed is simply ignored, so the system will continue using whatever seed was previously set. In this case, the random seed will not be set from the cloud, and setting the seed is left to up you. EEPROM EEPROM emulation allocates a region of the devices built-in Flash memory to act as EEPROM. Unlike true EEPROM, flash doesnt suffer from write wear with each write to each individual address. Instead, the page suffers wear when it is filled. Each write will add more data to the page until it is full, causing a page erase. The EEPROM functions can be used to store small amounts of data in Flash that will persist even after the device resets after a deep sleep or is powered off. length() Returns the total number of bytes available in the emulated EEPROM. The Core has 127 bytes of emulated EEPROM. The Photon and Electron have 2047 bytes of emulated EEPROM. put() This function will write an object to the EEPROM. You can write single values like int and float or group multiple values together using struct to ensure that all values of the struct are updated together. address is the start address (int) of the EERPOM locations to write. It must be a value between 0 and EEPROM. length()-1 object is the object data to write. The number of bytes to write is automatically determined from the type of object. The object data is first compared to the data written in the EEPROM to avoid writing values that havent changed. If the Photon loses power before the write finishes, the partially written data will be ignored. If you write several objects to EEPROM, make sure they dont overlap: the address of the second object must be larger than the address of the first object plus the size of the first object. You can leave empty room between objects in case you need to make the first object bigger later. get() This function will retrieve an object from the EEPROM. Use the same type of object you used in the put call. address is the start address (int) of the EERPOM locations to read. It must be a value between 0 and EEPROM. length()-1 object is the object data that would be read. The number of bytes read is automatically determined from the type of object. The default value of bytes in the EEPROM is 255 (hexadecimal 0xFF) so reading an object on a new Photon will return an object filled with 0xFF. One trick to deal with default data is to include a version field that you can check to see if there was valid data written in the EEPROM. read() Read a single byte of data from the emulated EEPROM. address is the address (int) of the EERPOM location to read When reading more than 1 byte, prefer get() over multiple read() since its faster. write() Write a single byte of data to the emulated EEPROM. address is the address (int) of the EERPOM location to write to value is the byte data (uint8t) to write When writing more than 1 byte, prefer put() over multiple write() since its faster and it ensures consistent data even when power is lost while writing. clear() Erase all the EEPROM so that all reads will return 255 (hexadecimal 0xFF). Calling this function pauses processor execution (including code running in interrupts) for 800ms since no instructions can be fetched from Flash while the Flash controller is busy erasing both EEPROM pages. hasPendingErase() performPendingErase() Automatic page erase is the default behavior. This section describes optional functions the application can call to manually control page erase for advanced use cases. After enough data has been written to fill the first page, the EEPROM emulation will write new data to a second page. The first page must be erased before being written again. Erasing a page of Flash pauses processor execution (including code running in interrupts) for 500ms since no instructions can be fetched from Flash while the Flash controller is busy erasing the EEPROM page. This could cause issues in applications that use EEPROM but rely on precise interrupt timing. hasPendingErase() lets the application developer check if a full EEPROM page needs to be erased. When the application determines it is safe to pause processor execution to erase EEPROM it calls performPendingErase(). You can call this at boot, or when your device is idle if you expect it to run without rebooting for a long time. To estimate how often page erases will be necessary in your application, assume that it takes 2EEPROM. length() byte writes to fill a page (it will usually be more because not all bytes will always be updated with different values). If the application never calls performPendingErase() then the pending page erase will be performed when data is written using put() or write() and both pages are full. So calling performPendingErase() is optional and provided to avoid the uncertainty of a potential processor pause any time put() or write() is called. Backup RAM (SRAM) The STM32F2xx features 4KB of backup RAM. Unlike the regular RAM memory, the backup RAM is retained so long as power is provided to VIN or to VBAT. In particular this means that the data in backup RAM is retained when: the device goes into deep sleep mode the device is hardware or software reset (while maintaining power) power is removed from VIN but retained on VBAT (which will retain both the backup RAM and the RTC) Note that if neither VIN or VBAT is powered then the contents of the backup RAM will be lost for data to be retained, the device needs a power source. For persistent storage of data through a total power loss, please use the EEPROM library. Power Conditions and how they relate to Backup RAM initilization and data retention: Power Down Method 1 Note: If VBAT is floating when powering up for the first time, SRAM remains uninitialized. When using this feature for Backup RAM, it is recommended to have VBAT connected to a 3V3 or a known good power source on system first boot. When using this feature for Extra RAM, it is recommended to jumper VBAT to GND to ensure it always initializes on system first boot. Storing data in Backup RAM (SRAM) With regular RAM, data is stored in RAM by declaring variables. This tells the system to store these values in RAM so they can be changed. The system takes care of giving them initial values. Before they are set, they will have the initial value 0 if an initial value isnt specified. Variables stored in backup RAM follow a similar scheme but use an additional keyword retained : A retained variable is similar to a regular variable, with some key differences: it is stored in backup RAM - no space is used in regular RAM instead of being initialized on each program start, retained variables are initialized when the device is first powered on (with VIN, from being powered off with VIN and VBAT completely removed). When the device is powered on, the system takes care of setting these variables to their initial values. lastTemperature and numberOfPresses would be initialized to 0, while numberOfTriesRemaining would be initialized to 10. the last value set on the variable is retained as long as the device is powered from VIN or VBAT and is not hard reset . retained variables can be updated freely just as with regular RAM variables and operate just as fast as regular RAM variables. Heres some typical use cases for retained variables: storing data for use after waking up from deep sleep storing data for use after power is removed on VIN, while power is still applied to VBAT (with coin cell battery or super capacitor) storing data for use after a hardware or software reset Finally, if you dont need the persistence of retained variables, you can consider them simply as 4KB of extra RAM to use. Enabling Backup RAM (SRAM) Backup RAM is disabled by default, since it does require some maintenance power which may not be desired on some low-powered projects. Backup RAM consumes roughly 5uA or less on VIN and 9uA or less on VBAT. Backup RAM is enabled with this code (to be placed at the top of your application outside of any functions): Making changes to the layout or types of retained variables When adding new retained variables to an existing set of retained variables, its a good idea to add them after the existing variables. this ensures the existing retained data is still valid even with the new code. For example, if we wanted to add a new variable char name50 we should add this after the existing retained variables: If instead we added name to the beginning or middle of the block of variables, the program would end up reading the stored values of the wrong variables. This is because the new code would be expecting to find the variables in a different memory location. Similarly, you should avoid changing the type of your variables as this will also alter the memory size and location of data in memory. This caveat is particularly important when updating firmware without power-cycling the device, which uses a software reset to reboot the device. This will allow previously retained variables to persist. During development, a good suggestion to avoid confusion is to design your application to work correctly when power is being applied for the first time, and all retained variables are initialized. If you must rearrange variables, simply power down the device (VIN and VBAT) after changes are made to allow reinitialization of retained variables on the next power up of the device. Its perfectly fine to mix regular and retained variables, but for clarity we recommend keeping the retained variables in their own separate block. In this way its easier to recognize when new retained variables are added to the end of the list, or when they are rearranged. Macros STARTUP() Typically an application will have its initialization code in the setup() function. This works well if a delay of a few seconds from power on/reset is acceptable. In other cases, the application wants to have code run as early as possible, before the cloud or network connection are initialized. The STARTUP() function instructs the system to execute the code early on in startup. The code referenced by STARTUP() is executed very early in the startup sequence, so its best suited to initializing digital I/O and peripherals. Networking setup code should still be placed in setup(). Although there is one notable exception - WiFi. selectAntenna() should be called from STARTUP() to select the default antenna before the Wi-Fi connection is made. Note that when startup code performs digital I/O, there will still be a period of at least few hundred milliseconds where the I/O pins are in their default power-on state, namely INPUT. Circuits should be designed with this in mind, using pullup/pulldown resistors as appropriate. PRODUCTID() When preparing software for your product, it is essential to include your product ID and version at the top of the firmware source code. You can find more details about the product ID and how to get yours in the Console guide. System Events System Events Overview System events are messages sent by the system and received by application code. They inform the application about changes in the system, such as when the system has entered setup mode, or when an Over-the-Air (OTA) update starts, or when the system is about to reset. System events are recieved by the application by registering a handler. The handler has this general format: Unused parameters can be removed from right to left, giving these additional function signatures: Heres an example of an application that listens for reset events so that the application is notified the device is about to reset. The application publishes a reset message to the cloud and turns off connected equipment before returning from the handler, allowing the device to reset. Some event types provide additional information. For example the buttonclick event provides a parameter with the number of button clicks: Registering multiple events with the same handler Its possible to subscribe to multiple events with the same handler in cases where you want the same handler to be notified for all the events. For example: To subscribe to all events, there is the placeholder allevents : System Events Reference These are the system events produced by the system, their numeric value (what you will see when printing the system event to Serial) and details of how to handle the parameter value. uuid 0.5.3 0.5.0 WARNING: MathRNG is now the default RNG method when using v4 of v5. If you wish to use CryptoRNG, import uuidutil. dart and use UuidUtil. cryptoRNG() with the RNG option dart-uuid Simple, fast generation of RFC4122 UUIDs. Heavily based on node-uuid by Robert Kieffer (I even copied this readme over and modified it.) Primarily becaue it works, well written, and so on. Generate RFC4122 version 1, version 4, or version 5 UUIDs Runs in dartvm and browsers. Cryptographically strong random number generation on all platforms Annotated source code Getting Started Instructions Open a command line and cd to your projects root folder In your pubspec, add an entry for dart-uuid to your dependencies (example below) pub install If you wish to run tests, go into packages/dart-uuid/ and run dart test/uuidtest. dart Pubspec There are 2 options. Directly from git, or from pub. dartlang. org pub. dartlang. org: (you can use any instead of a version if you just want the latest always) Then create some ids. API uuid. v1( ) Generate and return a RFC4122 v1 (timestamp-based) UUID. options - (Map) Optional uuid state to apply. Properties may include: node - (List) Node id as List of 6 bytes (per 4.1.6). Default: Randomnly generated ID. clockseq - (Number between 0 - 0x3fff) RFC clock sequence. Default: An internally maintained clockseq is used. msecs - (Number) Time in milliseconds since unix Epoch. Default: The current time is used. nsecs - (Number between 0-9999) additional time, in 100-nanosecond units. Ignored if msecs is unspecified. Default: internal uuid counter is used, as per 4.2.1.2. buffer - (List) Array or buffer where UUID bytes are to be written. offset - (Int) Starting index in buffer at which to begin writing. Returns buffer. if specified, otherwise the string form of the UUID Example: Generate string UUID with fully-specified options Example: In-place generation of two binary IDs uuid. v4( ) Generate and return a RFC4122 v4 UUID. options - (Map) Optional uuid state to apply. Properties may include: random - (Number16) List of 16 numbers (0-255) to use in place of randomly generated values rng - (Function) Random generator to use. A Custom function that returns an list16 of byte values or 1 of 2 provided. namedArgs - (MapltSymbol, dynamic) The arguments and values you want to pass to your function. positionalArgs - (List) The positional arguments for your functions. if any. buffer - (List) Array or buffer where UUID bytes are to be written. offset - (Number) Starting index in buffer at which to begin writing. Returns buffer. if specified, otherwise the string form of the UUID Example: Generate string UUID with different RNG method Example: Generate string UUID with different RNG method and named parameters Example: Generate string UUID with different RNG method and positional parameters Example: Generate string UUID with fully-specified options Example: Generate two IDs in a single buffer uuid. v5(String namespace, String name, ) Generate and return a RFC4122 v5 UUID. options - (Map) Optional uuid state to apply. Properties may include: randomNamespace - (Boolean) Default True. Returns if you want a v4 generated namespace (true) or NAMESPACENIL (false) buffer - (List) Array or buffer where UUID bytes are to be written. offset - (Number) Starting index in buffer at which to begin writing. Returns buffer. if specified, otherwise the string form of the UUID Example: Generate string UUID with fully-specified options Example: Generate two IDs in a single buffer uuid. parse(String uuid, ) uuid. unparse(List buffer, ) Parse and unparse UUIDs id - (String) UUID(-like) string buffer - (List) Array or buffer where UUID bytes are to be written. Default: A new Array or Buffer is used offset - (Int Number) Starting index in buffer at which to begin writing. Default: 0 Example parsing and unparsing a UUID string For more examples or usage, check my test implementations. Testing N/A as I have not used or tested this in the browser. But there are users of this library that do, and reported that it does infact work. Benchmarking Its pretty quick, but no official benchmarking. Release notes Merged pull request to support crypto 2.0.0 Support convert 2.0.0 Merged pull request to upgrade crypto library to 1.0.0. Merged pull request for various updates and cleanup. Reverted back to custom AES implementation. Moved RNG methods to UuidUtil (import package:uuid/uuidutil. dart) Fixed a potential bug with custom RNG method passing and added more ways to pass in custom RNG functions. Cleaned up and refactored some stuff. Using only v1 is only 67kb of js, Using only v4 is 97kb. Using crypt v4 is 118kb. Using both v1 and non-crypto v4 is 126kb. Default RNG for v4 is now the mathRNG function. If you wish to use cryptoRNG, import UuidUtil and pass in cryptoRNG. Updated README. md with more examples and usages. Updated Tests. Changed initCipher location so that if you ever only use v1 UUIDs, you will get a very small Dart2JS output compared to v4 or v5 that do load it. Use Cipher base. dart, as I dont need entropy generators, and this allows me to merge client/server together again and fix many issues this caused. Update pubspec to allow installation of the latest Cipher 0.7. Updated to latest Cipher at 0.6.0. This created a breaking change in the imports. Please make sure you update your code. Fixed problem when creating v4 UUIDs too fast, it would create duplicate UUIDs. Pegging cipher to 0.4.0 temporarily for browser support Using new version of cipher. Dart 1.0 Readiness Switched from custom AES to cipher package AES. Adjusting usage of constants. Fixing tests. randomint Beschreibung int randomint ( int min. int max ) Generates cryptographic random integers that are suitable for use where unbiased results are critical, such as when shuffling a deck of cards for a poker game. Die Zufallsquellen, die fr diese Funktion verwendet werden, sind folgende: Unter Windows wird immer CryptGenRandom() verwendet. Auf anderen Plattformen, wird arc4randombuf() verwendet, wenn es verfgbar ist. Dies ist im Allgemeinen nur unter BSD-Derivation oder Systemen mit libbsd der Fall. Schlgt obiges fehl, wird /dev/arandom verwendet, falls verfgbar. Ist /dev/arandom nicht verfgbar, dann wird /dev/urandom als Fallback verwendet. Ist keine der zuvor aufgezhlten Quellen verfbar, wird ein Error geworfen. Hinweis . Although this function was added to PHP in PHP 7.0, a raquo userland implementation is available for PHP 5.2 to 5.6, inclusive. Parameter-Liste The lowest value to be returned, which must be PHPINTMIN or higher. The highest value to be returned, which must be less than or equal to PHPINTMAX . Rckgabewerte Returns a cryptographically secure random integer in the range min to max. Inclusive. Fehler/Exceptions If an appropriate source of randomness cannot be found, an Exception will be thrown. If invalid parameters are given, a TypeError will be thrown. If max is less than min. an Error will be thrown. Beispiele ltphp vardump ( randomint ( 100. 999 )) vardump ( randomint (- 1000. 0 )) gt Here is a simple backporting function, it works for PHP gt 5.1 ltphp if ( functionexists ( randomint )) function randomint ( min. max ) if ( functionexists ( mcryptcreateiv )) triggererror ( mcrypt must be loaded for randomint to work. EUSERWARNING ) return null if ( isint ( min ) . isint ( max )) triggererror ( min and max must be integer values. EUSERNOTICE ) min (int) min max (int) max if ( min gt max ) triggererror ( max cant be lesser than min. EUSERWARNING ) return null range counter max - min bits 1 while ( counter gtgt 1 ) bits bytes (int) max ( ceil ( bits / 8 ), 1 ) bitmask pow ( 2. bits ) - 1 if ( bitmask gt PHPINTMAX ) bitmask PHPINTMAX do result hexdec ( bin2hex ( mcryptcreateiv ( bytes. MCRYPTDEVURANDOM ) ) ) amp bitmask while ( result gt range ) ltphp max 100 // number of random values test 1000000 array arrayfill ( 0. max. 0 ) for ( i 0 i lt test i ) array randomint ( 0. max - 1 ) function arrayFormatResult (amp item ) global test. max // try to avoid this nowdays ) perc ( item /( test / max ))- 1 item . . numberformat ( perc. 4. .. ). arraywalk ( array. arrayFormatResult ) printr ( array ) gt This function is based on Andrew Moores UUID generation function on the uniqid function it has been updated to use randomint() on PHP 7.0 or later yet continue to function with earlier versions using mtrand(). function generateUUIDv4() if(versioncompare(PHPVERSION,7.0.0, lt) ) return sprintf(04x04x-04x-04x-04x-04x04x04x, // 32 bits for timelow mtrand(0, 0xffff), mtrand(0, 0xffff), // 16 bits for timemid mtrand(0, 0xffff), // 16 bits for timehiandversion, // four most significant bits holds version number 4 mtrand(0, 0x0fff) 0x4000, // 16 bits, 8 bits for clkseqhires, // 8 bits for clkseqlow, // two most significant bits holds zero and one for variant DCE1.1 mtrand(0, 0x3fff) 0x8000, // 48 bits for node mtrand(0, 0xffff), mtrand(0, 0xffff), mtrand(0, 0xffff) ) else return sprintf(04x04x-04x-04x-04x-04x04x04x, // 32 bits for timelow randomint(0, 0xffff), randomint(0, 0xffff), // 16 bits for timemid randomint(0, 0xffff), // 16 bits for timehiandversion, // four most significant bits holds version number 4 randomint(0, 0x0fff) 0x4000, // 16 bits, 8 bits for clkseqhires, // 8 bits for clkseqlow, // two most significant bits holds zero and one for variant DCE1.1 randomint(0, 0x3fff) 0x8000, // 48 bits for node randomint(0, 0xffff), randomint(0, 0xffff), randomint(0, 0xffff) )

No comments:

Post a Comment