Adicionada nova estrutura de comunicação serial com Arduino

parent 2cccff53
//Bibliotecas
#include <avr/io.h> //inclui biblioteca de input/output do AVR
#include <avr/eeprom.h> //inclui biblioteca de EEPROM
#include <avr/interrupt.h> //inclui biblioteca de interrupt
#include <stdlib.h> //inclui biblioteca padrao
#include <string.h> //inclui biblioteca de strings
#include <math.h>
const byte buffSize = 40;
unsigned char inputBuffer[buffSize];
const char startMarker = '<';
const char endMarker = '>';
byte bytesRecvd = 0;
boolean readInProgress = false;
boolean newDataFromPC = false;
unsigned char rcvStatus = 0;
unsigned char prot;
unsigned char messageFromPC[buffSize] = {0};
unsigned char rcvProt[2][3];
unsigned int rcvParam[6][3];
void getDataFromPC() {
// receive data from PC and save it into inputBuffer
while(!Serial.available()){}
if(Serial.available() > 0) {
char x = Serial.read();
// the order of these IF clauses is significant
if (x == endMarker) {
readInProgress = false;
newDataFromPC = true;
inputBuffer[bytesRecvd] = 0;
strcpy(messageFromPC, inputBuffer); // copy it to messageFromPC
}
if(readInProgress) {
inputBuffer[bytesRecvd] = x;
bytesRecvd ++;
if (bytesRecvd == buffSize) {
bytesRecvd = buffSize - 1;
}
}
if (x == startMarker) {
bytesRecvd = 0;
readInProgress = true;
}
}
}
void saveAndReplyToPC() {
if (newDataFromPC) {
newDataFromPC = false;
rcvProt[0][prot] = messageFromPC[0];
rcvProt[1][prot] = messageFromPC[1];
rcvParam [0][prot]= ((messageFromPC[3]-1) & 255)<<8 | ((messageFromPC[2])&255);
rcvParam [1][prot]= ((messageFromPC[5]-1) & 255)<<8 | ((messageFromPC[4])&255);
rcvParam [2][prot]= ((messageFromPC[7]-1) & 255)<<8 | ((messageFromPC[6])&255);
rcvParam [3][prot]= ((messageFromPC[9]-1) & 255)<<8 | ((messageFromPC[8])&255);
rcvParam [4][prot]= ((messageFromPC[11]-1) & 255)<<8 | ((messageFromPC[10])&255);
rcvParam [5][prot]= ((messageFromPC[13]-1) & 255)<<8 | ((messageFromPC[12])&255);
Serial.print("<");
Serial.print("P");
Serial.print("R");
Serial.println(">");
}
}
void ReplyToPC() {
if (newDataFromPC) {
newDataFromPC = false;
Serial.print("<");
Serial.print("C");
Serial.print("R");
Serial.println(">");
}
}
//Função principal:
int main()
{
pinMode( 22 , OUTPUT ); //define saída 22 do Arduino para indicação com LED de protocolos ligados/desligados
digitalWrite( 22, LOW);
Serial.begin(9600); //inicia comunicação serial
Serial.println("<Arduino is ready>");
sei(); //reativa interrupts
while(1)
{
getDataFromPC();
if(messageFromPC[0]=='I' && messageFromPC[1]=='P')
{
digitalWrite(22, HIGH);
ReplyToPC();
}
else if(messageFromPC[0]=='A' && messageFromPC[1]=='P')
{
digitalWrite(22, LOW);
ReplyToPC();
}
else
{
//Recebe primeiro protocolo
prot = 0;
saveAndReplyToPC();
prot++;
//Recebe segundo protocolo...
}
}
return 0;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment