View Single Post
Old 04-19-2014, 12:26 PM   #43 (permalink)
P-hack
Master EcoModder
 
P-hack's Avatar
 
Join Date: Oct 2012
Location: USA
Posts: 1,408

awesomer - '04 Toyota prius
Thanks: 102
Thanked 252 Times in 204 Posts
Cool! FYI you have some synchronization bugs in your method 2. I prefer the method 2 approach as it has a controller in control that initiates communication so it can collate the results. Also fixed length binary data is easier to keep in sync than random length numbers as strings (and faster). Finally arrays make nice containers for lots of sensors, here is an example:

Code:
//example slave code
//hard code the first cell this slave is reading. (cell 1 is 0)
#define cellstart 8 //16 for the second slave
#define numcells  8  //2 for the second slave
void setup() {                
  Serial.begin(9600);
}

int readings [numcells];
void loop(){
  for(int x = 0;x<numcells;x++)
    for(int t=0;t<16;t++) //take several readings
      readings[x]=analogRead(x);
  if(Serial.available() > 0) {
    int cell = Serial.read(); //inquiry sent by Master
    //see if this board services the cell in question
    if(cell >= cellstart && cell < cellstart + numcells){
      Serial.write(lowByte(readings[cell-cellstart]));  //send low byte first
      Serial.write(highByte(readings[cell-cellstart]));     //then hi byte
    }
  }
}
Code:
//master example
//model 2, with byte level communication and arrays/iteration
#define numcells 18


void setup() {                
  Serial.begin(9600);
}
int  readings [numcells];//easier to deal with lots of values in an array and loop over them
void loop() {
  for(int x = 0; x < 8;x++) //readings for cells 0-7 are "local"
    for(int t = 0; t < 16;t++)
      readings[x]=analogRead(x);
      
  for(int x = 8; x < numcells; x++){
    Serial.write(x); //send the cell number to the slaves
    while(Serial.available() <2) {} //wait for two bytes of adc
    readings[x] = Serial.read(); //load the low byte
    readings[x] += Serial.read()<<8; // fill in the high byte  
  }

//... do something interesting with all those readings
//i.e. convert them to actual cell voltages and look for high and low
int basevolt=0;
  for(int x = 0; x < numcells; x++){
    int cellvolt=readings[x]-basevolt;
    basevolt=basevolt+cellvolt;
    
  //  lcd.clear();
   // lcd.goto((x%5)*4,x/20);
    //lcd.print(cellvolt); //10 bit value of the cell voltage
    
  }

  delay(500);               // wait for a second
}
note, you might want to shuffle the cell starts and the local loop so that you have some ADC ports on the master for current and temp and ?

Last edited by P-hack; 04-19-2014 at 12:48 PM..
  Reply With Quote
The Following User Says Thank You to P-hack For This Useful Post:
mechman600 (04-19-2014)