Hardware Reference
In-Depth Information
You need to load the code from Listing 6-3 onto the Arduino to use it as the sensor. The code sets up pins 2
through 11 with the register to demonstrate the same function as pinMode() . The code then counts a variable of
type unsigned int up to a value of 1024 so that the count will not continue to the maximum 16-bit value of 65535,
truncating the count to 10 bits by an AND mask. The code then shifts the data to match the proper pins and masks out
unneeded bits with the bitwise AND , placing the data in respective registers. Because the Arduino IDE is built on top
of the AVR C compiler, nothing needs to be included or declared to use the register names; they can just be typed and
work the same way as any variable.
manipulating the registers directly is an advanced programming technique that may not work consistently
on all arduino-capable boards. Check the pin mapping for the specific board and the data sheet for the register.
For example, the arduino mega PORTB controls pins 10 through 13 as the upper four bits and pins 50 through 53 for the
lower four bits.
Caution
Listing 6-3. Sensor code
unsigned int manipVar=0; // the only variable needed to achieve output
void setup() {
DDRD = DDRD | 0b11111100; // set pins 2-7 as output or leave pins 1,2
// alone for serial comunications
DDRB = DDRB | 0b00001111; // set 8-11 as output, leaving the rest alone
} // end void setup()
void loop() {
manipVar++; // any manipulation can be performed on manipVar
manipVar &= 0b0000001111111111; // mask that resets manipVar when 1024 is
// reached
PORTD = (manipVar << 2) & 0b11111100;// shift left by 2 bits then mask
// to get pins 2-7 straight out of manipVar
// then write value to pins on pins 2-7
PORTB = (manipVar >> 6) & 0b00001111;// shift right by nibble+crumb
// to set the value for pins 8-11
delay (1000); // to match refresh of sensor type
} // end void loop()
Verifying the Code
With the code uploaded to both Arduinos and the breadboard populated, plug in the reader and start the serial
monitor. The same information that was displayed in the last example will print to the screen this time, with
approximately 0.0048V per step, or about 0.5°C and the same temperature range.
This method reduces the jitter that is associated with the RC filter and matches the maximum resolution of
the ADC, making it a better choice to simulate an analog sensor. The disadvantages are the number of pins used,
the number of parts, and the advanced programming method required to achieve a clean count. With the setup
demonstrated in this section minus the delay, it takes around 4ms to count from 0 back to 0, making a ~250HZ
sawtooth wave and about 4ms between output changes. If the code is kept small, it is feasible to make a lightweight
function generator out of an Arduino by looping a byte array; it is also feasible to simulate piezoelectric knock
sensors.
 
 
Search WWH ::




Custom Search