2021-09-08
2. Class time
2.1. Operations on bits
…instead of signed/unsigned integers
Bitwise operations:
-
AND (
&
) -
OR (
|
) -
XOR (
^
, careful!!). How do you do \(y^x\) then? -
NOT (
~
)
Do you remember the difference between:
-
&
and&&
? -
|
and||
?- MSB
-
most significant Byte
- msb
-
most significant bit
Bit shifting:
-
Arithmetic
-
Logical
Shift left is like multiply by 2!
Shift right is like divide by 2! What if the number is negative? (msb is 1)
-> modern compilers are smart enough to do this without your "help." If you do not immediately know what will happen if the most-significant-bit is a 1
and you shift right, then do not be tricky.
If you intend to multiply by 2, then just say x = foo * 2; . Be careful with integer division, though x = foo / 2 is relatively safe.
|
2.2. Activity
What does this code do?
// x: 8-bit value. k: bit position to set, range is 0-7. b: set bit to this, either 1 or 0
unsigned char SetBit(unsigned char x, unsigned char k, unsigned char b) {
return (b ? (x | (0x01 << k)) : (x & ~(0x01 << k)) );
// Set bit to 1 Set bit to 0
}
-→ do you even remember what ?
does or is called??
Your task with a partner:
-
Paste this code into Notepad++
-
Rewrite the comments to be reasonable and actually helpful
-
Now that you are clear on what the code is supposed to do, rewrite the code to be easy to read.
-
Paste your code into a text snippet in the
#microcontrollers
Slack channel so everyone can see (see demo)
2.3. Airbag control
(did not make it here during class time)
A car has a sensor that sets A to the passenger’s weight (e.g., if the passenger weighs 130 pounds, A7..A0 will equal 10000010). Write a RIM C program that enables the car’s airbag system (B0=1) if the passenger’s weight is 105 pounds or greater. Also, illuminate an "Airbag off" light (by setting B1=1) if weight > 5 pounds but weight < 105 pounds.
-
How do you verify that the code works correctly? This is different than compiling and loading without errors.
-
How many tests does this require?