Here is my code:
Code: Select all
#include <Wire.h>
#include <Adafruit_MCP4725.h>
Adafruit_MCP4725 dac; // creates DAC object
Adafruit_MCP4725 dac_1; //creates DAC_1 object
int led = 3; // led pinOut assignment
int ledOn = 255; // assigns led brightness to the variable
int ledOff = 0; // assigns led brightness to the variable
const byte numChars = 18; //check sum variable to prevent corrupt packets
char receivedChars[numChars]; // array to hold string variable
char tempChars[numChars]; //temporary array for parsing
//variables to hold new data
char messageFromPC[numChars]= {0};
int DeviceID =0; //initialize variable
int SensorValueFromPC = 0; //initialize variable
boolean newData = false; //initialize variable
int ConvertedValue = 0; //initialize variable
void setup(){
Serial.begin(9600);
dac.begin(0x62);
dac_1.begin(0x63);
pinMode(led, OUTPUT);
}
void loop(){
recvWithStartEndMarkers();
if (newData == true){
strcpy(tempChars, receivedChars); //this temp copy is necessary to protect original data becuase strtok() used in parsedata() replaces commas with \0
parseData();
showParsedData();
newData = false;
}
}
void recvWithStartEndMarkers(){
static boolean recvInProgress = false;
static byte ndx = 0;
char startMarker = '<'; //Identifys beginning of Package
char endMarker = '>'; //Identifys end of Package
char rc;
while (Serial.available() > 0 && newData == false) {
rc = Serial.read();
if (recvInProgress == true) {
if (rc != endMarker){
receivedChars[ndx] = rc;
ndx++;
if (ndx >=numChars){
ndx = numChars -1;
}
}
else{
receivedChars[ndx] = '\0'; //terminate the string
recvInProgress = false;
ndx = 0;
newData = true;
}
}
else if(rc == startMarker){
recvInProgress = true;
}
}
}
void parseData(){ //splits the packaged data into parts
char * strtokIndx; //this is used by strtok() as a index
strtokIndx = strtok(tempChars,","); //get first part- the string
strcpy(messageFromPC, strtokIndx); //copys the string to messageFromPC
strtokIndx = strtok(NULL,","); //this continues where the previous call left
DeviceID = atoi(strtokIndx); //converts this part to integer
strtokIndx = strtok(NULL,",");
SensorValueFromPC = atoi(strtokIndx); // converts this part to a integer
ConvertedValue = map(SensorValueFromPC, 190, 1023, 0, 4095);
}
void showParsedData(){ //This Function will send the converted value to the appropriate DAC.
if (DeviceID == 1){
dac.setVoltage(ConvertedValue, false); //send to DAC
analogWrite(led, ledOn); // Turns on LED
}
else if (DeviceID == 2){
dac_1.setVoltage(ConvertedValue, false); //sends to DAC_1
analogWrite(led, ledOff); // Turns of LED
}
}