Sharer é um .NET e uma biblioteca Arduino . Ele permite que um aplicativo de desktop leia/grava variáveis e funções de chamada remota no Arduino , usando o protocolo Sharer, que acumula uma comunicação serial. Sharer foi desenvolvido inicialmente para o projeto Ballcuber (https://ballcuber.github.io), mas agora é uma biblioteca independente;).
// C#
var connection = new SharerConnection ( "COM3" , 115200 ) ;
connection . Connect ( ) ; Observação: Para algumas placas, como Micro e Leonardo, é necessário definir os sinais RTS e DTR com as propriedades RtsEnable e DtrEnable .
// C# - My Arduino code has a function : int Sum(int a, byte b);
var result = connection . Call ( "Sum" , 10 , 12 ) ;
// result.Status : OK
// result.Type : int
// result.Value : 22 // C# - Read all digital pins : digitalRead(0) to digitalRead(13)
for ( int i = 0 ; i <= 13 ; i ++ ) {
var digitalValue = connection . Call ( "digitalRead" , i ) ;
// digitalValue.Status : OK
// digitalValue.Type : bool
// digitalValue.Value : true or false
} // C# - Definition of all functions
var functions = connection . Functions ;
// functions[0].Name : function name
// functions[0].ReturnType : enum void, int, long, ...
// functions[0].Arguments[0].Name // Name of first argument
// functions[0].Arguments[0].Type // enum void, int, long, ... // C#
connection . WriteVariable ( "myVar" , 15 ) ; // returns true if writting OK // C# - Write simultaneously several variables by passing a List<WriteVariable>()
connection . WriteVariables ( listOfVariablesToWrite ) ; // C# - Definition of all variables
var variables = connection . Variables ;
// variables[0].Name : variable name
// variables[0].Type : enum int, long, ... // C#
var value = connection . ReadVariable ( "myVar" ) ;
// value.Status : OK
// value.Value : 12 // C# - Read simultaneously several variables
var values = connection . ReadVariables ( new string [ ] { "myVar" , "anotherVar" , "yetAnother" } ) ; // C#
var info = connection . GetInfos ( ) ;
// info.Board : Arduino UNO
// info.CPUFrequency : 16000000 (Hz)
// a lot more : info.CPlusPlusVersion, info.FunctionMaxCount, info.VariableMaxCount, ... Você pode enviar e receber mensagens clássicas na porta serial com as funções WriteUserData . Além disso, o evento UserDataReceived é aumentado quando os dados são enviados pelo Arduino.
Aviso: não é possível ler ou gravar variáveis e chamar funções em seu manipulador de eventos UserDataReceived .
// C#
connection . WriteUserData ( "Hello!" ) ;
connection . WriteUserData ( 12.2 ) ;
connection . WriteUserData ( new byte [ ] { 0x12 , 0x25 , 0xFF } ) ;
// Event raised when new user data sent by Arduino
connection . UserDataReceived += UserDataReceived ; // C++ Arduino
# include < Sharer.h >
// A simple function that sums an integer and a byte and return an integer
int Sum ( int a, byte b) {
return a + b;
}
// a simple integer
int myVar = 25 ;
void setup () {
Sharer. init ( 115200 ); // Init Serial communication with 115200 bauds
// Expose this function to Sharer : int Sum(int a, byte b)
Sharer_ShareFunction ( int , Sum, int , a, byte, b);
// Share system functions
Sharer_ShareFunction ( bool , digitalRead, uint8_t , pin);
Sharer_ShareVoid (pinMode, uint8_t , pin);
// Expose this variable to Sharer so that the desktop application can read/write it
Sharer_ShareVariable ( int , myVar);
}
// Run Sharer engine in the main Loop
void loop () {
Sharer. run ();
}Sharer é dividido em 2 repositórios, um para as fontes Arduino e o outro para fontes .NET
O Sharer está disponível no gerente da biblioteca disponível nas Tools/Manage Libraries... Basta procurar Sharer e instalar a versão mais recente.
Faça o download do Sharer Library Archive: https://github.com/rufus31415/sharer/releases/latest/download/sharer.zip
Sharer foi testado com Arduino Uno, Nano, Mega e devido. Pode funcionar com outros conselhos. Extrair para obter um diretório de compartilhador em seu diretório "bibliotecas" Arduino: C:Program Files (x86)ArduinolibrariesSharer
Você pode aproveitar os exemplos reiniciando seu Arduino IDE e acessar o File / examples / Sharer .
Sharer.net está disponível no NUGET: https://www.nuget.org/packages/sharer/
Use esta linha de comando para instalá -la com seu gerenciador de pacotes:
Install-Package Sharer
A Assembléia Sharer.dll pode ser baixada aqui: https://github.com/rufus31415/sharer.net/releases/latest/download/sharrasssemblies.zip
Este arquivo contém o Nuget Package Sharer.nupkg e o Sharer.dll compilados em AnyCPU Release para os seguintes metas:
O exemplo do Windows Forms requer .NET Framework 3.5. Pode ser baixado aqui: https://github.com/rufus31415/sharer.net/releases/latest/download/sharerwindowsformsexample.zip
O exemplo do console é executado com o .NET Core 3.0. Mas você não precisa de tempo de execução para executá -lo. Os exemplos independentes de console estão disponíveis aqui:
© RUFUS31415 Consulte o arquivo de licença para obter detalhes.
O arquivo de cabeçalho <sharer.h> deve ser incluído.
Na função setup() , o Sharer é inicializado passando um Baudrate para function Sharer.init(...) . Chame internamente Serial.init() com o mesmo baudrate.
Na função loop() , Sharer.run() deve ser chamado. Ele executa o kernel interno do Sharer que decodifica os comandos recebidos.
# include < Sharer.h >
void setup () {
Sharer. init ( 115200 );
}
void loop () {
Sharer. run ();
}Você também pode inicializar o Sharer com outro fluxo, como o Serial2 do Arduino devido se você usar o Serial2 para comunicar -se com o aplicativo de desktop:
void setup () {
// Initialize with another Serial interface
Serial2. begin ( 9600 );
Sharer. init (Serial2);
} Para adicionar uma variável na lista de variáveis compartilhadas, você deve ligar para o macro Sharer_ShareVariable . Seu primeiro argumento é o tipo de variável, e o segundo é o seu nome. Essa macro permite que o Sharer tenha um ponteiro para a variável, seu nome, seu tipo e seu tamanho de memória.
byte myByteVar;
long myLongVar;
int myIntArray[ 2 ];
void setup () {
Sharer. init ( 115200 );
Sharer_ShareVariable (byte, myByteVar);
Sharer_ShareVariable ( long , myLongVar);
Sharer_ShareVariable ( int , myIntArray[ 0 ]);
Sharer_ShareVariable ( int , myIntArray[ 1 ]);
} Para adicionar uma variável na lista de funções compartilhadas, você deve ligar para o macro Sharer_ShareFunction . Seu primeiro argumento é o tipo devolvido, e o segundo é o seu nome. A seguir, argumentos da macro descrevem o argumento da função compartilhada por seu tipo e seu nome. Não há limite no número de argumentos que você pode compartilhar, mas todos os argumentos devem ser compartilhados.
O compartilhamento de métodos de classe não é suportado e as funções compartilhadas devem ser funções gratuitas (funções estáticas não-membros).
Você pode compartilhar suas próprias funções, mas todas as funções do sistema como Analogread, DigitalRead, DigitalWrite, Millis, ...
int Sum ( int a, byte b) {
return a + b;
}
void setup () {
Sharer. init ( 115200 );
// Share your function to Sharer : int Sum(int a, byte b)
Sharer_ShareFunction ( int , Sum, int , a, byte, b);
// Sharer system functions
Sharer_ShareFunction ( int , analogRead, uint8_t , pin);
Sharer_ShareFunction ( bool , digitalRead, uint8_t , pin);
} As funções vazias são funções sem o tipo devolvido. Você deve chamar a macro Sharer_ShareVoid para compartilhar uma função vazia. O primeiro argumento é o seu nome, seguido pelo tipo e nome de cada argumento.
void TurnLEDOn ( void ) {
pinMode ( 13 , OUTPUT);
digitalWrite ( 13 , true );
}
void SetLEDState ( bool state) {
pinMode ( 13 , OUTPUT);
digitalWrite ( 13 , state);
}
void setup () {
Sharer. init ( 115200 );
// Share your void fuctions
Sharer_ShareVoid (TurnLEDOn);
Sharer_ShareVoid (SetLEDState, bool , state);
// Sharer system void functions
Sharer_ShareVoid (digitalWrite, uint8_t , pin);
}A classe Sharer herda do fluxo, para que você possa usar as seguintes funções. Por favor, nunca use o sharer.print (), sharer.println () ou sharer.write () dentro de uma função compartilhada, a escrita de que será ignorada.
void loop () {
Sharer. run ();
// gets the number of bytes available in the stream
int available = Sharer. available ();
// reads last reveided byte (-1 if no data to read)
int lastByte = Sharer. read ();
// Empty the stream
Sharer. flush ();
// reads data from the serial buffer until the target is found
// returns, true if data is found
bool found = Sharer. find ( " string to find " );
// Returns the next byte of incoming serial data without removing it from the internal serial buffer
// Successive calls to peek() will return the same character
int nextByte = Sharer. peek ();
// reads characters from the serial buffer into a String
String str = Sharer. readString ();
// Looks for the next valid integer in the incoming serial
int lastInt = Sharer. parseInt ();
lastInt = Sharer. parseInt (SKIP_ALL); // all characters other than digits or a minus sign are ignored when scanning the stream for an integer. This is the default mode
lastInt = Sharer. parseInt (SKIP_NONE); // nothing is skipped, and the stream is not touched unless the first waiting character is valid.
lastInt = Sharer. parseInt (SKIP_WHITESPACE); // only tabs, spaces, line feeds, and carriage returns are skipped.
// returns the first valid floating point number from the Serial buffer
float lastFloat = Sharer. parseFloat ();
lastFloat = Sharer. parseFloat (SKIP_ALL); // all characters other than a minus sign, decimal point, or digits are ignored when scanning the stream for a floating point number. This is the default mode.
lastFloat = Sharer. parseFloat (SKIP_NONE); // Nothing is skipped, and the stream is not touched unless the first waiting character is valid.
lastFloat = Sharer. parseFloat (SKIP_WHITESPACE); // only tabs, spaces, line feeds, and carriage returns are skipped.
// Prints ASCII encoded string
Sharer. print ( 85 ); // sends the string "85"
Sharer. print ( 1.23456 ); // sends the string "1.23"
Sharer. print ( ' N ' ); // sends the string "N"
Sharer. print ( " Hello world. " ); // sends the string "Hello world."
Sharer. print ( 78 , BIN); // sends the string "1001110"
Sharer. print ( 78 , OCT); // sends the string "116"
Sharer. print ( 78 , DEC); // sends the string "78"
Sharer. print ( 78 , HEX); // sends the string "4E"
Sharer. print ( 1.23456 , 0 ); // sends the string "1"
Sharer. print ( 1.23456 , 2 ); // sends the string "1.23"
Sharer. print ( 1.23456 , 4 ); // sends the string "1.2345"
Sharer. println ( " Hello ;) " ); // send the string and a new line "Hello ;)n"
Sharer. println (); // just sends a new line
// Write a single byte
Sharer. write ( 0x12 );
} Você pode alterar os limites do Sharer editando as constantes do arquivo C:Program Files (x86)ArduinolibrariesSharersrcSharerConfig.h .
// maximum number of shared functions
# define _SHARER_MAX_FUNCTION_COUNT 16
// maximum number of shared variables
# define _SHARER_MAX_VARIABLE_COUNT 32
// circle buffer size for user serial message
# define _SHARER_USER_RECEIVE_BUFFER_SIZE 64
// maximum number of call to Serial.read() each time Sharer.Run() is called
# define _SHARER_MAX_BYTE_READ_PER_RUN 1000 Você pode encontrar aqui a documentação completa do sharer.net: /sharer.net/sharer.net.documentation.md.
Um comando leva menos de 10ms a ser chamado em um Arduino UNO (comando + resposta) em 115200 bauds. O protocolo é otimizado para não ter strings para decodificar, apenas um fluxo binário para interpretar, byte byte. A pegada de memória foi otimizada usando a macro f () e progmem para armazenar nomes de variável, função e argumentos no flash.
Sharer usa um protocolo exclusivo chamado Protocolo Sharer. Todos os comandos seriais recebidos pelo Arduino são interpunhados.
Para continuar, eu prometo ...
Tenho algumas idéias para estender os recursos do compartilhamento como:
Se você estiver interessado em me ajudar no desenvolvimento do Sharer, terei o maior prazer em receber solicitações de recursos. O garfo também é bem -vindo;)