void MudbusYun::Run(){ Runs = 1 + Runs * (Runs < 999); //****************** Read from socket **************** MbServer.noListenOnLocalhost(); if (first == LOW){ MbServer.begin(); Serial.println("MbServer Begin"); first = HIGH; } if(millis() > (PreviousActivityTime + 60000)){ if(Active){ Active = false; #ifdef MbDebug Serial.println("Mb not active"); #endif } } if(client.connected()){ Reads = 1 + Reads * (Reads < 999); int i = 0; while(client.available()){ ByteArray[i] = client.read(); i++; } SetFC(ByteArray[7]); //Byte 7 of request is FC if(!Active){ Active = true; PreviousActivityTime = millis(); #ifdef MbDebug Serial.println("Mb active"); #endif } } else {client = MbServer.accept();} int Start, WordDataLength, ByteDataLength, CoilDataLength, MessageLength; //****************** Read Coils ********************** if(FC == MB_FC_READ_COILS){ Start = word(ByteArray[8],ByteArray[9]); CoilDataLength = word(ByteArray[10],ByteArray[11]); ByteDataLength = CoilDataLength / 8; if(ByteDataLength * 8 < CoilDataLength) ByteDataLength++; CoilDataLength = ByteDataLength * 8; #ifdef MbDebug Serial.print(" MB_FC_READ_COILS S="); Serial.print(Start); Serial.print(" L="); Serial.println(CoilDataLength); #endif //Number of bytes after this one. ByteArray[5] = ByteDataLength + 3; //Number of bytes after this one (or number of bytes of data). ByteArray[8] = ByteDataLength; for(int i = 0; i < ByteDataLength ; i++){ for(int j = 0; j < 8; j++){ bitWrite(ByteArray[9 + i], j, C[Start + i * 8 + j]); } } MessageLength = ByteDataLength + 9; client.write(ByteArray, MessageLength); Writes = 1 + Writes * (Writes < 999); FC = MB_FC_NONE; } //****************** Read Registers ****************** if(FC == MB_FC_READ_REGISTERS){ Start = word(ByteArray[8],ByteArray[9]); WordDataLength = word(ByteArray[10],ByteArray[11]); ByteDataLength = WordDataLength * 2; #ifdef MbDebug Serial.print(" MB_FC_READ_REGISTERS S="); Serial.print(Start); Serial.print(" L="); Serial.println(WordDataLength); #endif //Number of bytes after this one. ByteArray[5] = ByteDataLength + 3; //Number of bytes after this one (or number of bytes of data). ByteArray[8] = ByteDataLength; for(int i = 0; i < WordDataLength; i++){ ByteArray[ 9 + i * 2] = highByte(R[Start + i]); ByteArray[10 + i * 2] = lowByte(R[Start + i]); } MessageLength = ByteDataLength + 9; client.write(ByteArray, MessageLength); Writes = 1 + Writes * (Writes < 999); FC = MB_FC_NONE; } //****************** Write Coil ********************** if(FC == MB_FC_WRITE_COIL){ Start = word(ByteArray[8],ByteArray[9]); C[Start] = word(ByteArray[10],ByteArray[11]) > 0; #ifdef MbDebug Serial.print(" MB_FC_WRITE_COIL C"); Serial.print(Start); Serial.print("="); Serial.println(C[Start]); #endif ByteArray[5] = 2; //Number of bytes after this one. MessageLength = 8; client.write(ByteArray, MessageLength); Writes = 1 + Writes * (Writes < 999); FC = MB_FC_NONE; } //****************** Write Register ****************** if(FC == MB_FC_WRITE_REGISTER){ Start = word(ByteArray[8],ByteArray[9]); R[Start] = word(ByteArray[10],ByteArray[11]); #ifdef MbDebug Serial.print(" MB_FC_WRITE_REGISTER R"); Serial.print(Start); Serial.print("="); Serial.println(R[Start]); #endif ByteArray[5] = 6; //Number of bytes after this one. MessageLength = 12; client.write(ByteArray, MessageLength); Writes = 1 + Writes * (Writes < 999); FC = MB_FC_NONE; } //****************** Write Multiple Coils ********************** //Function codes 15 & 16 by Martin Pettersson http://siamect.com if(FC == MB_FC_WRITE_MULTIPLE_COILS){ Start = word(ByteArray[8],ByteArray[9]); CoilDataLength = word(ByteArray[10],ByteArray[11]); ByteDataLength = CoilDataLength / 8; if(ByteDataLength * 8 < CoilDataLength) ByteDataLength++; CoilDataLength = ByteDataLength * 8; #ifdef MbDebug Serial.print(" MB_FC_WRITE_MULTIPLE_COILS S="); Serial.print(Start); Serial.print(" L="); Serial.println(CoilDataLength); #endif //Number of bytes after this one. ByteArray[5] = ByteDataLength + 5; for(int i = 0; i < ByteDataLength ; i++){ for(int j = 0; j < 8; j++){ C[Start + i * 8 + j] = bitRead( ByteArray[13 + i], j); } } MessageLength = 12; client.write(ByteArray, MessageLength); Writes = 1 + Writes * (Writes < 999); FC = MB_FC_NONE; } //****************** Write Multiple Registers ****************** //Function codes 15 & 16 by Martin Pettersson http://siamect.com if(FC == MB_FC_WRITE_MULTIPLE_REGISTERS){ Start = word(ByteArray[8],ByteArray[9]); WordDataLength = word(ByteArray[10],ByteArray[11]); ByteDataLength = WordDataLength * 2; #ifdef MbDebug Serial.print(" MB_FC_READ_REGISTERS S="); Serial.print(Start); Serial.print(" L="); Serial.println(WordDataLength); #endif //Number of bytes after this one. ByteArray[5] = ByteDataLength + 3; for(int i = 0; i < WordDataLength; i++){ R[Start + i] = word(ByteArray[ 13 + i * 2],ByteArray[14 + i * 2]); } MessageLength = 12; client.write(ByteArray, MessageLength); Writes = 1 + Writes * (Writes < 999); FC = MB_FC_NONE; } #ifdef MbDebug Serial.print("Mb runs: "); Serial.print(Runs); Serial.print(" reads: "); Serial.print(Reads); Serial.print(" writes: "); Serial.print(Writes); Serial.println(); #endif }
/* || @description || | Return true if the button has been pressed || # */ bool Button::wasPressed(void) { return bitRead(state, CURRENT); }
/* || @description || | Return the bitRead(state,CURRENT) of the switch || # || || @return true if button is pressed */ bool Button::isPressed(void) { //save the previous value bitWrite(state, PREVIOUS, bitRead(state, CURRENT)); //get the current status of the pin if (digitalRead(pin) == mode) { //currently the button is not pressed bitWrite(state, CURRENT, false); } else { //currently the button is pressed bitWrite(state, CURRENT, true); } //handle state changes if (bitRead(state, CURRENT) != bitRead(state, PREVIOUS)) { //the state changed to PRESSED if (bitRead(state, CURRENT) == true) { numberOfPresses++; pressedStartTime = millis(); //start timing triggeredHoldEvent = false; if (cb_onPress) { cb_onPress(*this); //fire the onPress event } } else //the state changed to RELEASED { if (cb_onRelease) { cb_onRelease(*this); //fire the onRelease event } if (cb_onClick) { cb_onClick(*this); //fire the onClick event AFTER the onRelease } //reset states (for timing and for event triggering) pressedStartTime = -1; } //note that the state changed bitWrite(state, CHANGED, true); } else { //note that the state did not change bitWrite(state, CHANGED, false); //should we trigger a onHold event? if (pressedStartTime != -1 && !triggeredHoldEvent) { if (millis() - pressedStartTime > holdEventThreshold) { if (cb_onHold) { cb_onHold(*this); triggeredHoldEvent = true; } } } } return bitRead(state, CURRENT); }
/* ============================================================================= =========================================================================== */ void LIDARLite::read(char myAddress, int numOfBytes, byte arrayToSave[2], bool monitorBusyFlag, char LidarLiteI2cAddress){ int busyFlag = 0; if(monitorBusyFlag){ busyFlag = 1; } int busyCounter = 0; while(busyFlag != 0){ Wire.beginTransmission((int)LidarLiteI2cAddress); Wire.write(0x01); int nackCatcher = Wire.endTransmission(); if(nackCatcher != 0){Serial.println("> nack");} Wire.requestFrom((int)LidarLiteI2cAddress,1); busyFlag = bitRead(Wire.read(),0); busyCounter++; if(busyCounter > 9999){ if(errorReporting){ int errorExists = 0; Wire.beginTransmission((int)LidarLiteI2cAddress); Wire.write(0x01); int nackCatcher = Wire.endTransmission(); if(nackCatcher != 0){Serial.println("> nack");} Wire.requestFrom((int)LidarLiteI2cAddress,1); errorExists = bitRead(Wire.read(),0); if(errorExists){ unsigned char errorCode[] = {0x00}; Wire.beginTransmission((int)LidarLiteI2cAddress); // Get the slave's attention, tell it we're sending a command byte Wire.write(0x40); delay(20); int nackCatcher = Wire.endTransmission(); // "Hang up the line" so others can use it (can have multiple slaves & masters connected) if(nackCatcher != 0){Serial.println("> nack");} Wire.requestFrom((int)LidarLiteI2cAddress,1); errorCode[0] = Wire.read(); delay(10); Serial.print("> Error Code from Register 0x40: "); Serial.println(errorCode[0]); delay(20); Wire.beginTransmission((int)LidarLiteI2cAddress); Wire.write((int)0x00); Wire.write((int)0x00); nackCatcher = Wire.endTransmission(); if(nackCatcher != 0){Serial.println("> nack");} } } goto bailout; } } if(busyFlag == 0){ Wire.beginTransmission((int)LidarLiteI2cAddress); Wire.write((int)myAddress); int nackCatcher = Wire.endTransmission(); if(nackCatcher != 0){Serial.println("NACK");} Wire.requestFrom((int)LidarLiteI2cAddress, numOfBytes); int i = 0; if(numOfBytes <= Wire.available()){ while(i < numOfBytes){ arrayToSave[i] = Wire.read(); i++; } } } if(busyCounter > 9999){ bailout: busyCounter = 0; Serial.println("> Bailout"); } }
boolean IOClass::GetChannel(byte Channel) { return bitRead(IOPorts,Channel); }
void CButton::run() { bitWrite(state,PREVIOUS,bitRead(state,CURRENT)); timing[PREVIOUS] = timing[CURRENT]; bitWrite(state,CURRENT,(digitalRead(pin) != mode)); timing[CURRENT] = millis(); if (bitRead(state,CURRENT) != bitRead(state,PREVIOUS)){ bitWrite(state,CHANGED,true); timing[CHANGED] = timing[CURRENT]; }else{ bitWrite(state,CHANGED,false); } /* check if we need to reset a sequence that has been recorded * and is aged. * */ if(stopCountingSequence==false){ if(stateChanged()){ /* check if was a transition from * pressed to release */ if(!bitRead(state,PREVIOUS)){ /* new Pressure start * reset the timeout for the sequence */ timing[START_OF_SEQ] = millis(); shortCounted=longCounted=false; } }else{ /* status doesn't change*/ if(isPressed()){ if( shortCounted==false && isExpired(timing[START_OF_SEQ],shortPushMilli) ){ /* count it only once*/ shortPressureCount++; shortCounted=true; timing[START_OF_SEQ] = millis(); } if( longCounted==false && isExpired(timing[START_OF_SEQ],longPushMilli) ){ /* count it only once*/ longPressureCount++; shortPressureCount--; longCounted=true; timing[START_OF_SEQ] = millis(); } if(longCounted && isExpired(timing[START_OF_SEQ],resetSequenceMilli)){ shortPressureCount=longPressureCount=0; stopCountingSequence=false; } } } } if(!isPressed() && (longCounted || shortCounted)){ if(isExpired(timing[START_OF_SEQ],timeOut4SequenceMilli) && stopCountingSequence==false ){ stopCountingSequence=true; } if(stopCountingSequence && isExpired(timing[START_OF_SEQ],expireSequenceMilli)){ shortPressureCount=longPressureCount=0; stopCountingSequence=false; } } delay(20); }
//****************** Recieve data for ModBusSlave **************** void MgsModbus::MbsRun() { //****************** Read from socket **************** WiFiClient client = MbServer.available(); if(client.available()) { delay(10); int i = 0; while(client.available()) { MbsByteArray[i] = client.read(); i++; } MbsFC = SetFC(MbsByteArray[7]); //Byte 7 of request is FC } int Start, WordDataLength, ByteDataLength, CoilDataLength, MessageLength; //****************** Read Coils (1 & 2) ********************** if(MbsFC == MB_FC_READ_COILS || MbsFC == MB_FC_READ_DISCRETE_INPUT) { Start = word(MbsByteArray[8],MbsByteArray[9]); CoilDataLength = word(MbsByteArray[10],MbsByteArray[11]); ByteDataLength = CoilDataLength / 8; if(ByteDataLength * 8 < CoilDataLength) ByteDataLength++; CoilDataLength = ByteDataLength * 8; MbsByteArray[5] = ByteDataLength + 3; //Number of bytes after this one. MbsByteArray[8] = ByteDataLength; //Number of bytes after this one (or number of bytes of data). for(int i = 0; i < ByteDataLength ; i++) { MbsByteArray[9 + i] = 0; // To get all remaining not written bits zero for(int j = 0; j < 8; j++) { bitWrite(MbsByteArray[9 + i], j, GetBit(Start + i * 8 + j)); } } MessageLength = ByteDataLength + 9; client.write((uint8_t*)MbsByteArray, MessageLength); MbsFC = MB_FC_NONE; } //****************** Read Registers (3 & 4) ****************** if(MbsFC == MB_FC_READ_REGISTERS || MbsFC == MB_FC_READ_INPUT_REGISTER) { Start = word(MbsByteArray[8],MbsByteArray[9]); WordDataLength = word(MbsByteArray[10],MbsByteArray[11]); ByteDataLength = WordDataLength * 2; MbsByteArray[5] = ByteDataLength + 3; //Number of bytes after this one. MbsByteArray[8] = ByteDataLength; //Number of bytes after this one (or number of bytes of data). for(int i = 0; i < WordDataLength; i++) { MbsByteArray[ 9 + i * 2] = highByte(MbData[Start + i]); MbsByteArray[10 + i * 2] = lowByte(MbData[Start + i]); } MessageLength = ByteDataLength + 9; client.write((uint8_t*)MbsByteArray, MessageLength); MbsFC = MB_FC_NONE; } //****************** Write Coil (5) ********************** if(MbsFC == MB_FC_WRITE_COIL) { Start = word(MbsByteArray[8],MbsByteArray[9]); if (word(MbsByteArray[10],MbsByteArray[11]) == 0xFF00){SetBit(Start,true);} if (word(MbsByteArray[10],MbsByteArray[11]) == 0x0000){SetBit(Start,false);} MbsByteArray[5] = 2; //Number of bytes after this one. MessageLength = 8; client.write((uint8_t*)MbsByteArray, MessageLength); MbsFC = MB_FC_NONE; } //****************** Write Register (6) ****************** if(MbsFC == MB_FC_WRITE_REGISTER) { Start = word(MbsByteArray[8],MbsByteArray[9]); MbData[Start] = word(MbsByteArray[10],MbsByteArray[11]); MbsByteArray[5] = 6; //Number of bytes after this one. MessageLength = 12; client.write((uint8_t*)MbsByteArray, MessageLength); MbsFC = MB_FC_NONE; } //****************** Write Multiple Coils (15) ********************** if(MbsFC == MB_FC_WRITE_MULTIPLE_COILS) { Start = word(MbsByteArray[8],MbsByteArray[9]); CoilDataLength = word(MbsByteArray[10],MbsByteArray[11]); MbsByteArray[5] = 6; for(int i = 0; i < CoilDataLength; i++) { SetBit(Start + i,bitRead(MbsByteArray[13 + (i/8)],i-((i/8)*8))); } MessageLength = 12; client.write((uint8_t*)MbsByteArray, MessageLength); MbsFC = MB_FC_NONE; } //****************** Write Multiple Registers (16) ****************** if(MbsFC == MB_FC_WRITE_MULTIPLE_REGISTERS) { Start = word(MbsByteArray[8],MbsByteArray[9]); WordDataLength = word(MbsByteArray[10],MbsByteArray[11]); ByteDataLength = WordDataLength * 2; MbsByteArray[5] = 6; for(int i = 0; i < WordDataLength; i++) { MbData[Start + i] = word(MbsByteArray[ 13 + i * 2],MbsByteArray[14 + i * 2]); } MessageLength = 12; client.write((uint8_t*)MbsByteArray, MessageLength); MbsFC = MB_FC_NONE; } }
/** * Method called by the TIMER2 Interrupt Service Routine. Transmits each * bit of the current TX packet. */ void IR::handleTx() { // If the IR configuration's gap duration has expired since the last packet was sent, // call the 'sendPacket()' method, which initializes the IR packet for transmission if (this->lastPacketTime < millis() - 50/*(this->irConfig.gapDuration / 1000)*/) { this->lastPacketTime = millis(); this->sendPacket(); } // If TX is not enabled (for instance, if no commands have been received from the // IR controller), turn the IR transmitter off if (!this->txEnabled) { this->irOff(); return; } // If we've reached the end of the current packet, disable TX and turn the IR // transmitter off if (this->currentPacketBit == 255) { this->txEnabled = 0; this->irOff(); return; } // If we have not sent the start pulse for the current packet, and the IR // configuration has defined a start pulse duration, transmit the start pulse. // NOTE: as the Air Swimmer packet does not utilize a start bit, this // functionality is untested and incomplete. /*if (this->irConfig.startPulseDuration > 0 && !this->startPulseSent) { this->startPulseSent = 1; this->currentPulseDelay = this->irConfig.startPulseDuration; this->irOn(); return; }*/ // Current pulse delay hasn't expired; stop processing if (this->lastBitTime > micros() - this->currentPulseDelay) { return; } // If we haven't yet sent a gap pulse, configure the transmitter // to send the pulse gap if (!this->inPulseGap) { this->inPulseGap = 1; this->currentPulseDelay = this->irConfig.pulseGapDuration; this->markGap(); return; } // We are no longer in a pulse gap this->inPulseGap = 0; // Configure the pulse delay based on the current packet bit. if (bitRead(this->packetBuffer, this->currentPacketBit - 1)) { this->currentPulseDelay = this->irConfig.longPulseDuration; } else { this->currentPulseDelay = this->irConfig.shortPulseDuration; } // Enable IR for sending the next bit this->markPulse(); // Decrement the current packet position --this->currentPacketBit; }
// Process a MIDI Note On message void MidiSostenutoPedal::noteOn(uint8_t channel, uint8_t note, uint8_t velocity) { bitSet(prePedalNotes[channel & 0xF][(note & 0x7F) / 32], (note & 0x7F) % 32); // Remember as channel pre-pedal note if (bitRead(pressed, channel & 0xF)) // If pedal pressed, reset channel held note bitClear(heldNotes[channel & 0xF][(note & 0x7F) / 32], (note & 0x7F) % 32); handleNoteOn(channel, note, velocity); }
void TM1628::setSeg(byte addr, byte num) { for(int i=0; i<7; i++){ bitWrite(buffer[i*2], seg_addr[addr], bitRead(NUMBER_FONT[num],i)); } }
void TM1628::setChar(byte addr, byte chr) { for(int i=0; i<7; i++){ bitWrite(buffer[i*2], seg_addr[addr], bitRead(FONT_DEFAULT[chr - 0x20],i)); } update(); }
int mcp23008::gpioDigitalReadFast(uint8_t pin){ int temp = 0; if (pin < 8) temp = bitRead(_gpioState,pin);//0...7 return temp; }
int pca9555::gpioDigitalReadFast(uint8_t pin) { int temp = 0; if (pin < 15) temp = bitRead(_gpioState,pin); return temp; }
byte readPixel(byte whichBuffer[][SHREGISTERS], byte x, byte y) // left upper pixel is x0, y0. it does account for the not connected pins on the sh-registers. { return bitRead(whichBuffer[y][(x+NONVISABLES)/(SHREGISTERS+1)], 7-((x+NONVISABLES)%8)); }
/* Read the state of an individual pin by reading the internal library register, NOT the chip so take care! This is extremely fast and not use any SPI calls. Parameters pin:0...7/15 Returns 0 or 1 */ bool gpio_MCP23SXX::gpioDigitalReadFast(uint8_t pin) { bool temp = 0; if (pin < _ports) temp = bitRead(_gpioState,pin); return temp; }
bool Atm::isShiftHold(AtmEngine::Func func) { unsigned char i = func>>3; return (bool)bitRead(IS_SHIFT_HOLD[i],func-(i*8)); }
boolean SST25VF016B::isReady(void) { byte statreg = readStatusRegistry(); return bitRead(statreg,0); }
bool Atm::isFuncFill(AtmEngine::Func func) const { unsigned char i = func>>3; return (bool)bitRead(IS_FUNC_FILL[i],func-(i*8)); }
void gameoflife::run(byte res) { static word current[15]; //current 16x16 playing fied static word next[15]; //next 16x16 playing field static byte emptycount; static byte Reset; //internal reset flag static byte frameOffset = 0; //offset for drawing frame static byte frameCount = 0; static byte genCount = 0; static byte resetFade = gameOfLifeResetFade - 1; byte xMod, yMod, alive, fadecount; CRGB fadeInColor, fadeOutColor, onColor; byte fadeInVal, fadeOutVal; if((Reset == 1) | (res == 1)) { //if reset flag is thrown resetFade++; if(resetFade != gameOfLifeResetFade) { //take time to fade colors fadeOutVal = 250 - (resetFade * 5); fadeOutColor = CRGB(fadeOutVal * gameOfLifeR, fadeOutVal * gameOfLifeG, fadeOutVal * gameOfLifeB); for(byte y = 0; y<10; y++) { //draw the current frame window for(byte x = 0; x<10; x++) { if( (bitRead(current[y], GOL_BUFFER_WRAP(x))==1) ) { //keep on all the way if the colonly isnt changing disp[CORDINATE(x,y)] = fadeOutColor; } } //Serial.println(fadeOutVal); } } else { for(byte i = 0; i< 15; i++) { current[i] = 0; //ramdomly populate playing field next[i] = random(0xFFFF); } Reset = 0; //set reset flag back to 0; emptycount = 0; //if the reset flag was thrown internally by a stagnated game reset stagnant frame count genCount = 0; resetFade = 0; } //Serial.println(resetFade); return; } //check each cell to update for next generation generation if(frameCount == 0) { for(byte y = 0; y<16; y++) { //check each row for(byte x = 0; x <16; x++) { //Check each column xMod =(15-((x + 15) % 15)); //flip x yMod = (y + 15) % 15; alive = 0; alive += bitRead(current[yMod+1], xMod); //right alive += bitRead(current[yMod+1], xMod+1); //down + right alive += bitRead(current[yMod+1], xMod-1); //down + left alive += bitRead(current[yMod-1], xMod-1); //up + right alive += bitRead(current[yMod-1], xMod); //up alive += bitRead(current[yMod-1], xMod+1); //up + right alive += bitRead(current[yMod], xMod+1); //left alive += bitRead(current[yMod], xMod-1); // down if (bitRead(current[yMod], xMod) == 1) { //check to see if cell lives or dies if ((alive < 2) || (alive > 3)) bitWrite(next[yMod], xMod, 0); //dies else bitWrite(next[yMod], xMod, 1); //lives } else { if (alive == 3) bitWrite(next[yMod], xMod, 1); //stays alive } } } //finish generation */ } fadeInVal = (frameCount * gameOfLifeNLFactor) ; //uncomment for non-linear brightness fadeOutVal = 250 - fadeInVal; // fadeInVal = linearPWM(frameCount * gameOfLifeLFactor); //uncomment for linear brightness // fadeOutVal = linearPWM((gameOfLifeTime - frameCount) * gameOfLifeLFactor); fadeInColor = CRGB(fadeInVal * gameOfLifeR, fadeInVal * gameOfLifeG, fadeInVal * gameOfLifeB); fadeOutColor = CRGB(fadeOutVal * gameOfLifeR, fadeOutVal * gameOfLifeG, fadeOutVal * gameOfLifeB); onColor = CRGB(255 * gameOfLifeR, 255 * gameOfLifeG, 255 * gameOfLifeB); for(byte y = 0; y<10; y++) { //draw the current frame window for(byte x = 0; x<10; x++) { if( (bitRead(current[y], GOL_BUFFER_WRAP(x))==0) && (bitRead(next[y], GOL_BUFFER_WRAP(x))==0)) { //keep on all the way if the colonly isnt changing disp[CORDINATE(x,y)] = CRGB::Black; } else if( (bitRead(current[y], GOL_BUFFER_WRAP(x))==1) && (bitRead(next[y], GOL_BUFFER_WRAP(x))==1) ) { //keep on all the way if the colonly isnt changing disp[CORDINATE(x,y)] = onColor; } else if( (bitRead(current[y], GOL_BUFFER_WRAP(x)) == 1) && (bitRead(next[y], GOL_BUFFER_WRAP(x))==0) ) { //fade current out disp[CORDINATE(x,y)] = fadeOutColor; } else { //fade next color in disp[CORDINATE(x,y)] = fadeInColor; } } } fadecount = 0; //seagnation variable if(frameCount == gameOfLifeTime) { //copy over and check for game stagnation frameCount = 0; genCount++; for(byte i = 0; i<16; i++) { //copy new frame to current frame if(((unsigned int)(next[i]) == ((unsigned int)(current[i]))) && (i < 10)) fadecount++; current[i] = next[i]; } //end for loop if(fadecount > 5) //if most of the frame has not moved emptycount++; //add 1 to emptycount else emptycount = 0; //reset emptycount to 0 to prevent false positives if((emptycount>5) || (genCount > gameOfLifeMaxGen)) //if game had been mostly stagnant for 15 frames in a row, throw internal reset Reset = 1; } else frameCount++; return; }
int SENSORS::getSensorValue(byte port, int deviceID) { int aInPin; int dInPin; int sensorValue; static int tempValue; if(port == 1){ aInPin = ADC_PIN_P1_1; dInPin = IO_PIN_P1_1; } else if (port == 2) { aInPin = ADC_PIN_P2_1; dInPin = IO_PIN_P2_1; } else if (port == 3) { aInPin = ADC_PIN_P3_1; dInPin = IO_PIN_P3_1; } else { //Serial.println("--> ERROR"); //Serial.print("--> Attempting to assign port: "); } switch (deviceID) { case 0: // UNKNOWN Sensor, pass in the ADC Value pinMode(aInPin, INPUT); sensorValue = analogRead(aInPin); return sensorValue; case 5: // Push Button Sensor pinMode(dInPin, INPUT); sensorValue = digitalRead(dInPin) * 1023; if (sensorValue==0) nOBJECTS.blinkLED(BLUE_LED_PIN); return sensorValue; case 6: // Light Sensor pinMode(aInPin, INPUT); sensorValue = analogRead(aInPin); return sensorValue; case 7: // PIR Sensor pinMode(dInPin, INPUT); sensorValue = digitalRead(dInPin) * 1023; if (sensorValue>0) nOBJECTS.blinkLED(GREEN_LED_PIN); return sensorValue; case 8: // DHT22 Humidity Sensor myDHT22.setPIN(dInPin); errorCode = myDHT22.readData(); if ((errorCode==DHT_ERROR_NONE) || (errorCode==DHT_ERROR_TOOQUICK)) { sensorValue = myDHT22.getHumidity() * 10 ; // make a single decimal float to int tempValue = myDHT22.getTemperatureC() * 10; // make a single decimal float to int return sensorValue; } else return 0; case 9: // DHT22 Temperature Sensor return tempValue; case 10: // Distance Sensor pinMode(aInPin, INPUT); sensorValue = analogRead(aInPin); return sensorValue; case 11: // 433Mhz Receiver - Not required to return anything // Special handling in doPort1() return -1; case 12: pinMode(aInPin, INPUT); sensorValue = analogRead(aInPin); if (sensorValue>0) nOBJECTS.blinkLED(RED_LED_PIN); return sensorValue; case 1002: // Relay Breakout pinMode(dInPin, OUTPUT); if (port == 1) sensorValue = bitRead(PORTC, 0); else if (port == 2) sensorValue = bitRead(PORTC, 1); else if (port == 3) sensorValue = bitRead(PORTC, 2); return sensorValue; default: // Invalid sensor ID return -1; } }
void ArduboyTones::nextTone() { uint16_t freq; uint16_t dur; long toggleCount; uint32_t ocrValue; #ifdef TONES_ADJUST_PRESCALER uint8_t tccrxbValue; #endif freq = getNext(); // get tone frequency if (freq == TONES_END) { // if freq is actually an "end of sequence" marker noTone(); // stop playing return; } tonesPlaying = true; if (freq == TONES_REPEAT) { // if frequency is actually a "repeat" marker tonesIndex = tonesStart; // reset to start of sequence freq = getNext(); } #ifdef TONES_VOLUME_CONTROL if (((freq & TONE_HIGH_VOLUME) || forceHighVol) && !forceNormVol) { toneHighVol = true; } else { toneHighVol = false; } #endif freq &= ~TONE_HIGH_VOLUME; // strip volume indicator from frequency #ifdef TONES_ADJUST_PRESCALER if (freq >= MIN_NO_PRESCALE_FREQ) { tccrxbValue = _BV(WGM32) | _BV(CS30); // CTC mode, no prescaling ocrValue = F_CPU / freq / 2 - 1; toneSilent = false; } else { tccrxbValue = _BV(WGM32) | _BV(CS31); // CTC mode, prescaler /8 #endif if (freq == 0) { // if tone is silent ocrValue = F_CPU / 8 / SILENT_FREQ / 2 - 1; // dummy tone for silence freq = SILENT_FREQ; toneSilent = true; bitClear(TONE_PIN_PORT, TONE_PIN); // set the pin low } else { ocrValue = F_CPU / 8 / freq / 2 - 1; toneSilent = false; } #ifdef TONES_ADJUST_PRESCALER } #endif if (!outputEnabled()) { // if sound has been muted toneSilent = true; } #ifdef TONES_VOLUME_CONTROL if (toneHighVol && !toneSilent) { // set pin 2 to the compliment of pin 1 if (bitRead(TONE_PIN_PORT, TONE_PIN)) { bitClear(TONE_PIN2_PORT, TONE_PIN2); } else { bitSet(TONE_PIN2_PORT, TONE_PIN2); } } else { bitClear(TONE_PIN2_PORT, TONE_PIN2); // set pin 2 low for normal volume } #endif dur = getNext(); // get tone duration if (dur != 0) { // A right shift is used to divide by 512 for efficency. // For durations in milliseconds it should actually be a divide by 500, // so durations will by shorter by 2.34% of what is specified. toggleCount = ((long)dur * freq) >> 9; }
void display_digit(const uint8_t digit, const uint8_t base_pin, const uint8_t bits) { for (uint8_t bit=0; bit < bits; ++bit) { digitalWrite(base_pin + bit, bitRead(digit, bit)); } }
void TMRpcm::play(char* filename, unsigned long seekPoint){ if(speakerPin != lastSpeakPin){ #if !defined (MODE2) setPin(); #else setPins(); #endif lastSpeakPin=speakerPin; } stopPlayback(); if(!wavInfo(filename)){ #if defined (debug) Serial.println("WAV ERROR"); #endif return; }//verify its a valid wav file if(seekPoint > 0){ seekPoint = (SAMPLE_RATE*seekPoint) + fPosition(); seek(seekPoint); //skip the header info } playing = 1; bitClear(optionByte,7); //paused = 0; if(SAMPLE_RATE > 45050 ){ SAMPLE_RATE = 24000; #if defined (debug) Serial.print("SAMPLE RATE TOO HIGH: "); Serial.println(SAMPLE_RATE); #endif } #if !defined (USE_TIMER2) //if(qual) if(bitRead(optionByte,6)){resolution = 10 * (800000/SAMPLE_RATE);} else{ resolution = 10 * (1600000/SAMPLE_RATE); } #else resolution = 255; if(SAMPLE_RATE < 9000){ *TCCRnB[tt] &= ~_BV(CS20); *TCCRnB[tt] |= _BV(CS21); }else{ *TCCRnB[tt] &= ~_BV(CS21); *TCCRnB[tt] |= _BV(CS20); } #endif byte tmp = (sFile.read() + sFile.peek()) / 2; #if defined(rampMega) if(bitRead(optionByte,5)){ *OCRnA[tt] = 0; *OCRnB[tt] = resolution; timerSt(); for(unsigned int i=0; i < resolution; i++){ *OCRnB[tt] = constrain(resolution-i,0,resolution); //if(bitRead(*TCCRnB[tt],0)){ // for(int i=0; i<10; i++){ // while(*TCNT[tt] < resolution-50){} // } //}else{ delayMicroseconds(150); //} } } bitClear(optionByte,5); #endif //rampUp = 0; unsigned int mod; if(volMod > 0){ mod = *OCRnA[tt] >> volMod; }else{ mod = *OCRnA[tt] << (volMod*-1); }
bool MMA8452Q::orientation(uint8_t *value) { *value = registerRead(PL_STATUS); return bitRead(*value, NEWLP); }
int max7318::gpioDigitalReadFast(uint8_t pin){ int temp = 0; if (pin < 16) temp = bitRead(_gpioState,pin); return temp; }
int MMA8452Q::backFront(uint8_t orient) { return bitRead(orient, BAFRO); }
/* || @description || | Return true if state has been changed || # */ bool Button::stateChanged(void) { return bitRead(state, CHANGED); }
/* Setup the entire chip The IOCON register! 7 6 5 4 3 2 1 0 MCP23S08 IOCON = NA NA SEQOP DISSLW HAEN ODR INTPOL NA MCP23S09 IOCON = NA NA SEQOP NA NA ODR INTPOL INTCC MCP23S17 IOCON = BANK MIRROR SEQOP DISSLW HAEN ODR INTPOL NA MCP23S18 IOCON = BANK MIRROR SEQOP NA NA ODR INTPOL INTCC ----------------------------------------------------------------------- 0b01101100 7: BANK: (Controls how the registers are addressed) 1 The registers associated with each port are separated into different banks 0 The registers are in the same bank (addresses are sequential) 6: MIRROR: (INT Pins Mirror bit) 1 The INT pins are internally connected 0 The INT pins are not connected. INTA is associated with PortA and INTB is associated with PortB 5: SEQOP: (Sequential Operation mode bit) 1 Sequential operation disabled, address pointer does not increment 0 Sequential operation enabled, address pointer increments. 4: DISSLW: (Slew Rate control bit for SDA output, only I2C) 3: HAEN: (Hardware Address Enable bit, SPI only) 1 Enables the MCP23S17 address pins 0 Disables the MCP23S17 address pins 2: ODR: (This bit configures the INT pin as an open-drain output) 1 Open-drain output (overrides the INTPOL bit). 0 Active driver output (INTPOL bit sets the polarity). 1: INTPOL: (This bit sets the polarity of the INT output pin) 1 Active high 0 Active low 0: INTCC: (Interrupt Clearing Control) 1 Reading INTCAP register clears the interrupt 0 Reading GPIO register clears the interrupt -------------------------------------------------------------------------- Parameter data:8bit or you can use _BANKOP | _HAEN (etc) Note. Each time gpioSetup is called, it reset the IOCON register first! */ bool gpio_MCP23SXX::gpioSetup(uint8_t data) { bool result = 1; if (_ports < 16){ _regIndex = 1; } else { _regIndex = 0; } _IOCON_setup = data; switch(_chip){ case MCP23S08: //need to clear something? if (bitRead(_IOCON_setup,7)) {_IOCON_setup &= ~(1 << 7); result = 0;}//NA if (bitRead(_IOCON_setup,6)) {_IOCON_setup &= ~(1 << 6); result = 0;}//NA if (bitRead(_IOCON_setup,0)) {_IOCON_setup &= ~(1 << 0); result = 0;}//NA break; case MCP23S09: if (bitRead(_IOCON_setup,7)) {_IOCON_setup &= ~(1 << 7); result = 0;}//NA if (bitRead(_IOCON_setup,6)) {_IOCON_setup &= ~(1 << 6); result = 0;}//NA if (bitRead(_IOCON_setup,4)) {_IOCON_setup &= ~(1 << 4); result = 0;}//NA if (bitRead(_IOCON_setup,3)) {_IOCON_setup &= ~(1 << 3); result = 0;}//NA _IOCON_setup |= (1 << 0);//always enable INTCC break; case MCP23S17: if (bitRead(_IOCON_setup,7)) _regIndex = 1;//1 if (bitRead(_IOCON_setup,0)) {_IOCON_setup &= ~(1 << 0); result = 0;}//NA break; case MCP23S18: if (bitRead(_IOCON_setup,7)) _regIndex = 1;//1 if (bitRead(_IOCON_setup,4)) {_IOCON_setup &= ~(1 << 4); result = 0;}//NA if (bitRead(_IOCON_setup,3)) {_IOCON_setup &= ~(1 << 3); result = 0;}//NA _IOCON_setup |= (1 << 0);//always enable INTCC break; case MCPNONE: return 0; break; } _IOCON_setup |= (1 << 5);//TODO: SEQOP always enabled in this library!? //CHECKTHIS! if (_ports < 16){ _GPIOwriteByte(MCP23XXX_IOCON[1], _IOCON_setup); //_sendData(MCP23XXX_IOCON[1], _IOCON_setup,true); } else { _GPIOwriteByte(MCP23XXX_IOCON[0], _IOCON_setup); //_sendData(MCP23XXX_IOCON[0], _IOCON_setup,true); } return result; }
boolean Plugin_005(byte function, struct NodoEventStruct *event, char *string) { boolean success=false; static byte Call_Status = 0x00; // Each bit represents one relative port. 0=not called before, 1=already called before. switch(function) { #ifdef PLUGIN_005_CORE case PLUGIN_COMMAND: { int DSTemp; // Temperature in 16-bit Dallas format. byte ScratchPad[12]; // Scratchpad buffer Dallas sensor. byte var=event->Par2; // Variabele die gevuld moet worden. byte RelativePort=event->Par1-1; UserVariablePayload(var,0x0011); // De Dallas sensor kan worden aangesloten op iedere digitale poort van de Arduino. In ons geval kiezen we er voor // om de sensor aan te sluiten op de Wired-Out poorten van de Nodo. Met Par2 is de Wired poort aangegeven. // 1 = WiredOut poort 1. DallasPin=PIN_WIRED_OUT_1+event->Par1-1; ClearEvent(event); // Ga uit van een default schone event. Oude eventgegevens wissen. noInterrupts(); while (!(bitRead(Call_Status, RelativePort))) { // if this is the very first call to the sensor on this port, reset it to wake it up boolean present=DS_reset(); bitSet(Call_Status, RelativePort); } boolean present=DS_reset();DS_write(0xCC /* rom skip */); DS_write(0x44 /* start conversion */); interrupts(); if(present) { delay(800); // uitleestijd die de sensor nodig heeft noInterrupts(); DS_reset(); DS_write(0xCC /* rom skip */); DS_write(0xBE /* Read Scratchpad */); // Maak de lijn floating zodat de sensor de data op de lijn kan zetten. digitalWrite(DallasPin,LOW); pinMode(DallasPin,INPUT); for (byte i = 0; i < 9; i++) // copy 8 bytes ScratchPad[i] = DS_read(); interrupts(); DSTemp = (ScratchPad[1] << 8) + ScratchPad[0]; TempFloat=float(DSTemp)*0.0625; // DS18B20 variant. Waarde terugstoppen in de variabele success=(UserVariableSet(var,TempFloat,PLUGIN_05_EVENT)!=-1); } break; } #endif // CORE #if NODO_MEGA case PLUGIN_MMI_IN: { char *TempStr=(char*)malloc(INPUT_COMMAND_SIZE); if(GetArgv(string,TempStr,1)) { if(strcasecmp(TempStr,PLUGIN_NAME)==0) { // Par1 en Par2 hoeven niet te worden geparsed omdat deze default al door de MMI invoer van de Nodo // worden gevuld indien het integer waarden zijn. Toetsen op bereiken moet nog wel plaats vinden. if(event->Par1>0 && event->Par1<=HARDWARE_WIRED_OUT_PORTS && event->Par2>0 && event->Par2<=USER_VARIABLES_MAX_NR) { success=true; event->Type = NODO_TYPE_PLUGIN_COMMAND; event->Command = 5; // Plugin nummer } } } free(TempStr); break; } case PLUGIN_MMI_OUT: { strcpy(string,PLUGIN_NAME); // Eerste argument=het commando deel strcat(string," "); strcat(string,int2str(event->Par1)); strcat(string,","); strcat(string,int2str(event->Par2)); break; } #endif //MMI } return success; }
// -------------------------------------------------------- // Check Write-protect bit uint8_t DS1302RTC::writeEN() { return !bitRead(readRTC(DS1302_ENABLE), DS1302_WP); }