110_quiz9.zig 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. // ----------------------------------------------------------------------------
  2. // Toggling, Setting, and Clearing Bits
  3. // ----------------------------------------------------------------------------
  4. //
  5. // Another exciting thing about Zig is its suitability for embedded
  6. // programming. Your Zig code doesn't have to remain on your laptop. You can
  7. // also deploy your code to microcontrollers! This means you can write Zig to
  8. // drive your next robot or greenhouse climate control system! Ready to enter
  9. // the exciting world of embedded programming? This exercise is designed to
  10. // give you a taste of what it's like to control registers in a
  11. // microcontroller. Let's get started!
  12. //
  13. // A common activity in microcontroller programming is setting and clearing
  14. // bits on input and output pins. This lets you control LEDs, sensors, motors
  15. // and more! In a previous exercise (097_bit_manipulation.zig) you learned how
  16. // to swap two bytes using the ^ (XOR - exclusive or) operator. In this
  17. // exercise, we'll take a closer look at bit manipulation and how we can write
  18. // code that sets and clears specific bits as we would if we were programming
  19. // the pins on a real microcontroller. Included at the end of this exercise are
  20. // some helper functions that demonstrate how we might make our code a little
  21. // more readable.
  22. //
  23. // Below is a pinout diagram for the famous ATmega328 AVR microcontroller used
  24. // as the primary microchip on popular microcontroller platforms like the
  25. // Arduino UNO.
  26. //
  27. // ============ PINOUT DIAGRAM FOR ATMEGA328 MICROCONTROLLER ============
  28. // _____ _____
  29. // | U |
  30. // (RESET) PC6 --| 1 28 |-- PC5
  31. // PD0 --| 2 27 |-- PC4
  32. // PD1 --| 3 26 |-- PC3
  33. // PD2 --| 4 25 |-- PC2
  34. // PD3 --| 5 24 |-- PC1
  35. // PD4 --| 6 23 |-- PC0
  36. // VCC --| 7 22 |-- GND
  37. // GND --| 8 21 |-- AREF
  38. // |-- PB6 --| 9 20 |-- AVCC
  39. // |-- PB7 --| 10 19 |-- PB5 --|
  40. // | PD5 --| 11 18 |-- PB4 --|
  41. // | PD6 --| 12 17 |-- PB3 --|
  42. // | PD7 --| 13 16 |-- PB2 --|
  43. // |-- PB0 --| 14 15 |-- PB1 --|
  44. // | |___________| |
  45. // \_______________________________/
  46. // |
  47. // PORTB
  48. //
  49. // Drawing inspiration from this diagram, we'll use the pins for PORTB as our
  50. // mental model for this exercise in bit manipulation. It should be noted that
  51. // in the following examples we are using ordinary variables, one of which we
  52. // have named PORTB, to simulate modifying the bits of real hardware registers.
  53. // But in actual microcontroller code, PORTB would be defined something like
  54. // this:
  55. // pub const PORTB = @as(*volatile u8, @ptrFromInt(0x25));
  56. //
  57. // This lets the compiler know not to make any optimizations to PORTB so that
  58. // the IO pins are properly mapped to our code.
  59. //
  60. // NOTE : To keep things simple, the following examples are given using type
  61. // u4, so applying the output to PORTB would only affect the lower four pins
  62. // PB0..PB3. Of course, there is nothing to prevent you from swapping the u4
  63. // with a u8 so you can control all 8 of PORTB's IO pins.
  64. const std = @import("std");
  65. const print = std.debug.print;
  66. const testing = std.testing;
  67. pub fn main() !void {
  68. var PORTB: u4 = 0b0000; // only 4 bits wide for simplicity
  69. // The LCD display on our robot is not behaving as expected. In order to
  70. // get it functioning properly, we must initialize it by sending the
  71. // correct sequence of half-bytes to PORTB's lower four pins.
  72. //
  73. // See if you can solve the following problems to get the lcd working and
  74. // reveal the message our robot has stored in his EEPROM.
  75. //
  76. // .--. .--.
  77. // | | | |
  78. // +--------------------------+
  79. // | +----------------------+ |
  80. // | | | |
  81. // | | XXXXXXXX XXXXXXXX | | <-- LCD
  82. // | | | |
  83. // | +----------------------+ |
  84. // | _________ |
  85. // | |_|_|_|_|_| |
  86. // | |
  87. // +--------------------------+
  88. // | |
  89. //
  90. // The last two problems throw you a bit of a curve ball. Try solving them
  91. // on your own. If you need help, scroll to the bottom to see some in depth
  92. // explanations on toggling, setting, and clearing bits in Zig.
  93. print("Toggle pins with XOR on PORTB\n", .{});
  94. print("-----------------------------\n", .{});
  95. PORTB = 0b1100;
  96. print(" {b:0>4} // (initial state of PORTB)\n", .{PORTB});
  97. print("^ {b:0>4} // (bitmask)\n", .{0b0101});
  98. PORTB ^= (1 << 1) | (1 << 0); // What's wrong here?
  99. checkAnswer(0b1001, PORTB);
  100. newline();
  101. PORTB = 0b1100;
  102. print(" {b:0>4} // (initial state of PORTB)\n", .{PORTB});
  103. print("^ {b:0>4} // (bitmask)\n", .{0b0011});
  104. PORTB ^= (1 << 1) & (1 << 0); // What's wrong here?
  105. checkAnswer(0b1111, PORTB);
  106. newline();
  107. print("Set pins with OR on PORTB\n", .{});
  108. print("-------------------------\n", .{});
  109. PORTB = 0b1001; // reset PORTB
  110. print(" {b:0>4} // (initial state of PORTB)\n", .{PORTB});
  111. print("| {b:0>4} // (bitmask)\n", .{0b0100});
  112. PORTB = PORTB ??? (1 << 2); // What's missing here?
  113. checkAnswer(0b1101, PORTB);
  114. newline();
  115. PORTB = 0b1001; // reset PORTB
  116. print(" {b:0>4} // (reset state)\n", .{PORTB});
  117. print("| {b:0>4} // (bitmask)\n", .{0b0100});
  118. PORTB ??? (1 << 2); // What's missing here?
  119. checkAnswer(0b1101, PORTB);
  120. newline();
  121. print("Clear pins with AND and NOT on PORTB\n", .{});
  122. print("------------------------------------\n", .{});
  123. PORTB = 0b1110; // reset PORTB
  124. print(" {b:0>4} // (initial state of PORTB)\n", .{PORTB});
  125. print("& {b:0>4} // (bitmask)\n", .{0b1011});
  126. PORTB = PORTB & ???@as(u4, 1 << 2); // What character is missing here?
  127. checkAnswer(0b1010, PORTB);
  128. newline();
  129. PORTB = 0b0111; // reset PORTB
  130. print(" {b:0>4} // (reset state)\n", .{PORTB});
  131. print("& {b:0>4} // (bitmask)\n", .{0b1110});
  132. PORTB &= ~(1 << 0); // What's missing here?
  133. checkAnswer(0b0110, PORTB);
  134. newline();
  135. newline();
  136. }
  137. // ************************************************************************
  138. // IN-DEPTH EXPLANATIONS BELOW
  139. // ************************************************************************
  140. // ------------------------------------------------------------------------
  141. // Toggling bits with XOR:
  142. // ------------------------------------------------------------------------
  143. // XOR stands for "exclusive or". We can toggle bits with the ^ (XOR)
  144. // bitwise operator, like so:
  145. //
  146. //
  147. // In order to output a 1, the logic of an XOR operation requires that the
  148. // two input bits are of different values. Therefore, 0 ^ 1 and 1 ^ 0 will
  149. // both yield a 1 but 0 ^ 0 and 1 ^ 1 will output 0. XOR's unique behavior
  150. // of outputing a 0 when both inputs are 1s is what makes it different from
  151. // the OR operator; it also gives us the ability to toggle bits by putting
  152. // 1s into our bitmask.
  153. //
  154. // - 1s in our bitmask operand, can be thought of as causing the
  155. // corresponding bits in the other operand to flip to the opposite value.
  156. // - 0s cause no change.
  157. //
  158. // The 0s in our bitmask preserve these values
  159. // -XOR op- ---expanded--- in the output.
  160. // _______________/
  161. // / /
  162. // 0110 1 1 0 0
  163. // ^ 1111 0 1 0 1 (bitmask)
  164. // ------ - - - -
  165. // = 1001 1 0 0 1 <- This bit was already cleared.
  166. // \_______\
  167. // \
  168. // We can think of these bits having flipped
  169. // because of the presence of 1s in those columns
  170. // of our bitmask.
  171. //
  172. // Now let's take a look at setting bits with the | operator.
  173. //
  174. // ------------------------------------------------------------------------
  175. // Setting bits with OR:
  176. // ------------------------------------------------------------------------
  177. // We can set bits on PORTB with the | (OR) operator, like so:
  178. //
  179. // var PORTB: u4 = 0b1001;
  180. // PORTB = PORTB | 0b0010;
  181. // print("PORTB: {b:0>4}\n", .{PORTB}); // output: 1011
  182. //
  183. // -OR op- ---expanded---
  184. // _ Set only this bit.
  185. // /
  186. // 1001 1 0 0 1
  187. // | 0010 0 0 1 0 (bit mask)
  188. // ------ - - - -
  189. // = 1011 1 0 1 1
  190. // \___\_______\
  191. // \
  192. // These bits remain untouched because OR-ing with
  193. // a 0 effects no change.
  194. //
  195. // ------------------------------------------------------------------------
  196. // To create a bit mask like 0b0010 used above:
  197. //
  198. // 1. First, shift the value 1 over one place with the bitwise << (shift
  199. // left) operator as indicated below:
  200. // 1 << 0 -> 0001
  201. // 1 << 1 -> 0010 <-- Shift 1 one place to the left
  202. // 1 << 2 -> 0100
  203. // 1 << 3 -> 1000
  204. //
  205. // This allows us to rewrite the above code like this:
  206. //
  207. // var PORTB: u4 = 0b1001;
  208. // PORTB = PORTB | (1 << 1);
  209. // print("PORTB: {b:0>4}\n", .{PORTB}); // output: 1011
  210. //
  211. // Finally, as in the C language, Zig allows us to use the |= operator, so
  212. // we can rewrite our code again in an even more compact and idiomatic
  213. // form: PORTB |= (1 << 1)
  214. // So now we've covered how to toggle and set bits. What about clearing
  215. // them? Well, this is where Zig throws us a curve ball. Don't worry we'll
  216. // go through it step by step.
  217. // ------------------------------------------------------------------------
  218. // Clearing bits with AND and NOT:
  219. // ------------------------------------------------------------------------
  220. // We can clear bits with the & (AND) bitwise operator, like so:
  221. // PORTB = 0b1110; // reset PORTB
  222. // PORTB = PORTB & 0b1011;
  223. // print("PORTB: {b:0>4}\n", .{PORTB}); // output -> 1010
  224. //
  225. // - 0s clear bits when used in conjuction with a bitwise AND.
  226. // - 1s do nothing, thus preserving the original bits.
  227. //
  228. // -AND op- ---expanded---
  229. // __________ Clear only this bit.
  230. // /
  231. // 1110 1 1 1 0
  232. // & 1011 1 0 1 1 (bit mask)
  233. // ------ - - - -
  234. // = 1010 1 0 1 0 <- This bit was already cleared.
  235. // \_______\
  236. // \
  237. // These bits remain untouched because AND-ing with a
  238. // 1 preserves the original bit value whether 0 or 1.
  239. //
  240. // ------------------------------------------------------------------------
  241. // We can use the ~ (NOT) operator to easily create a bit mask like 1011:
  242. //
  243. // 1. First, shift the value 1 over two places with the bit-wise << (shift
  244. // left) operator as indicated below:
  245. // 1 << 0 -> 0001
  246. // 1 << 1 -> 0010
  247. // 1 << 2 -> 0100 <- The 1 has been shifted two places to the left
  248. // 1 << 3 -> 1000
  249. //
  250. // 2. The second step in creating our bit mask is to invert the bits
  251. // ~0100 -> 1011
  252. // in C we would write this as:
  253. // ~(1 << 2) -> 1011
  254. //
  255. // But if we try to compile ~(1 << 2) in Zig, we'll get an error:
  256. // unable to perform binary not operation on type 'comptime_int'
  257. //
  258. // Before Zig can invert our bits, it needs to know the number of
  259. // bits it's being asked to invert.
  260. //
  261. // We do this with the @as (cast as) built-in like this:
  262. // @as(u4, 1 << 2) -> 0100
  263. //
  264. // Finally, we can invert our new mask by placing the NOT ~ operator
  265. // before our expression, like this:
  266. // ~@as(u4, 1 << 2) -> 1011
  267. //
  268. // If you are offput by the fact that you can't simply invert bits like
  269. // you can in languages such as C without casting to a particular size
  270. // of integer, you're not alone. However, this is actually another
  271. // instance where Zig is really helpful because it protects you from
  272. // difficult to debug integer overflow bugs that can have you tearing
  273. // your hair out. In the interest of keeping things sane, Zig requires
  274. // you simply to tell it the size of number you are inverting. In the
  275. // words of Andrew Kelley, "If you want to invert the bits of an
  276. // integer, zig has to know how many bits there are."
  277. //
  278. // For more insight into the Zig team's position on why the language
  279. // takes the approach it does with the ~ operator, take a look at
  280. // Andrew's comments on the following github issue:
  281. // https://github.com/ziglang/zig/issues/1382#issuecomment-414459529
  282. //
  283. // Whew, so after all that what we end up with is:
  284. // PORTB = PORTB & ~@as(u4, 1 << 2);
  285. //
  286. // We can shorten this with the &= combined AND and assignment operator,
  287. // which applies the AND operator on PORTB and then reassigns PORTB. Here's
  288. // what that looks like:
  289. // PORTB &= ~@as(u4, 1 << 2);
  290. //
  291. // ------------------------------------------------------------------------
  292. // Conclusion
  293. // ------------------------------------------------------------------------
  294. //
  295. // While the examples in this quiz have used only 4-bit wide variables,
  296. // working with 8 bits is no different. Here's a an example where we set
  297. // every other bit beginning with the two's place:
  298. // var PORTD: u8 = 0b0000_0000;
  299. // print("PORTD: {b:0>8}\n", .{PORTD});
  300. // PORTD |= (1 << 1);
  301. // PORTD = setBit(u8, PORTD, 3);
  302. // PORTD |= (1 << 5) | (1 << 7);
  303. // print("PORTD: {b:0>8} // set every other bit\n", .{PORTD});
  304. // PORTD = ~PORTD;
  305. // print("PORTD: {b:0>8} // bits flipped with NOT (~)\n", .{PORTD});
  306. // newline();
  307. //
  308. // // Here we clear every other bit beginning with the two's place.
  309. //
  310. // PORTD = 0b1111_1111;
  311. // print("PORTD: {b:0>8}\n", .{PORTD});
  312. // PORTD &= ~@as(u8, 1 << 1);
  313. // PORTD = clearBit(u8, PORTD, 3);
  314. // PORTD &= ~@as(u8, (1 << 5) | (1 << 7));
  315. // print("PORTD: {b:0>8} // clear every other bit\n", .{PORTD});
  316. // PORTD = ~PORTD;
  317. // print("PORTD: {b:0>8} // bits flipped with NOT (~)\n", .{PORTD});
  318. // newline();
  319. // ----------------------------------------------------------------------------
  320. // Here are some helper functions for manipulating bits
  321. // ----------------------------------------------------------------------------
  322. // Functions for setting, clearing, and toggling a single bit
  323. fn setBit(comptime T: type, byte: T, comptime bit_pos: T) !T {
  324. return byte | (1 << bit_pos);
  325. }
  326. test "setBit" {
  327. try testing.expectEqual(setBit(u8, 0b0000_0000, 3), 0b0000_1000);
  328. }
  329. fn clearBit(comptime T: type, byte: T, comptime bit_pos: T) T {
  330. return byte & ~@as(T, (1 << bit_pos));
  331. }
  332. test "clearBit" {
  333. try testing.expectEqual(clearBit(u8, 0b1111_1111, 0), 0b1111_1110);
  334. }
  335. fn toggleBit(comptime T: type, byte: T, comptime bit_pos: T) T {
  336. return byte ^ (1 << bit_pos);
  337. }
  338. test "toggleBit" {
  339. var byte = toggleBit(u8, 0b0000_0000, 0);
  340. try testing.expectEqual(byte, 0b0000_0001);
  341. byte = toggleBit(u8, byte, 0);
  342. try testing.expectEqual(byte, 0b0000_0000);
  343. }
  344. // ----------------------------------------------------------------------------
  345. // Some additional functions for setting, clearing, and toggling multiple bits
  346. // at once with a tuple because, hey, why not?
  347. // ----------------------------------------------------------------------------
  348. //
  349. fn createBitmask(comptime T: type, comptime bits: anytype) !T {
  350. comptime var bitmask: T = 0;
  351. inline for (bits) |bit| {
  352. if (bit >= @bitSizeOf(T)) return error.BitPosTooLarge;
  353. if (bit < 0) return error.BitPosTooSmall;
  354. bitmask |= (1 << bit);
  355. }
  356. return bitmask;
  357. }
  358. test "creating bitmasks from a tuple" {
  359. try testing.expectEqual(createBitmask(u8, .{0}), 0b0000_0001);
  360. try testing.expectEqual(createBitmask(u8, .{1}), 0b0000_0010);
  361. try testing.expectEqual(createBitmask(u8, .{2}), 0b0000_0100);
  362. try testing.expectEqual(createBitmask(u8, .{3}), 0b0000_1000);
  363. //
  364. try testing.expectEqual(createBitmask(u8, .{ 0, 4 }), 0b0001_0001);
  365. try testing.expectEqual(createBitmask(u8, .{ 1, 5 }), 0b0010_0010);
  366. try testing.expectEqual(createBitmask(u8, .{ 2, 6 }), 0b0100_0100);
  367. try testing.expectEqual(createBitmask(u8, .{ 3, 7 }), 0b1000_1000);
  368. try testing.expectError(error.BitPosTooLarge, createBitmask(u4, .{4}));
  369. }
  370. fn setBits(byte: u8, bits: anytype) !u8 {
  371. const bitmask = try createBitmask(u8, bits);
  372. return byte | bitmask;
  373. }
  374. test "setBits" {
  375. try testing.expectEqual(setBits(0b0000_0000, .{0}), 0b0000_0001);
  376. try testing.expectEqual(setBits(0b0000_0000, .{7}), 0b1000_0000);
  377. try testing.expectEqual(setBits(0b0000_0000, .{ 0, 1, 2, 3, 4, 5, 6, 7 }), 0b1111_1111);
  378. try testing.expectEqual(setBits(0b1111_1111, .{ 0, 1, 2, 3, 4, 5, 6, 7 }), 0b1111_1111);
  379. try testing.expectEqual(setBits(0b0000_0000, .{ 2, 3, 4, 5 }), 0b0011_1100);
  380. try testing.expectError(error.BitPosTooLarge, setBits(0b1111_1111, .{8}));
  381. try testing.expectError(error.BitPosTooSmall, setBits(0b1111_1111, .{-1}));
  382. }
  383. fn clearBits(comptime byte: u8, comptime bits: anytype) !u8 {
  384. const bitmask: u8 = try createBitmask(u8, bits);
  385. return byte & ~@as(u8, bitmask);
  386. }
  387. test "clearBits" {
  388. try testing.expectEqual(clearBits(0b1111_1111, .{0}), 0b1111_1110);
  389. try testing.expectEqual(clearBits(0b1111_1111, .{7}), 0b0111_1111);
  390. try testing.expectEqual(clearBits(0b1111_1111, .{ 0, 1, 2, 3, 4, 5, 6, 7 }), 0b000_0000);
  391. try testing.expectEqual(clearBits(0b0000_0000, .{ 0, 1, 2, 3, 4, 5, 6, 7 }), 0b000_0000);
  392. try testing.expectEqual(clearBits(0b1111_1111, .{ 0, 1, 6, 7 }), 0b0011_1100);
  393. try testing.expectError(error.BitPosTooLarge, clearBits(0b1111_1111, .{8}));
  394. try testing.expectError(error.BitPosTooSmall, clearBits(0b1111_1111, .{-1}));
  395. }
  396. fn toggleBits(comptime byte: u8, comptime bits: anytype) !u8 {
  397. const bitmask = try createBitmask(u8, bits);
  398. return byte ^ bitmask;
  399. }
  400. test "toggleBits" {
  401. try testing.expectEqual(toggleBits(0b0000_0000, .{0}), 0b0000_0001);
  402. try testing.expectEqual(toggleBits(0b0000_0000, .{7}), 0b1000_0000);
  403. try testing.expectEqual(toggleBits(0b1111_1111, .{ 0, 1, 2, 3, 4, 5, 6, 7 }), 0b000_0000);
  404. try testing.expectEqual(toggleBits(0b0000_0000, .{ 0, 1, 2, 3, 4, 5, 6, 7 }), 0b1111_1111);
  405. try testing.expectEqual(toggleBits(0b0000_1111, .{ 0, 1, 2, 3, 4, 5, 6, 7 }), 0b1111_0000);
  406. try testing.expectEqual(toggleBits(0b0000_1111, .{ 0, 1, 2, 3 }), 0b0000_0000);
  407. try testing.expectEqual(toggleBits(0b0000_0000, .{ 0, 2, 4, 6 }), 0b0101_0101);
  408. try testing.expectError(error.BitPosTooLarge, toggleBits(0b1111_1111, .{8}));
  409. try testing.expectError(error.BitPosTooSmall, toggleBits(0b1111_1111, .{-1}));
  410. }
  411. // ----------------------------------------------------------------------------
  412. // Utility functions
  413. // ----------------------------------------------------------------------------
  414. fn newline() void {
  415. print("\n", .{});
  416. }
  417. fn checkAnswer(expected: u4, answer: u4) void {
  418. if (expected != answer) {
  419. print("*************************************************************\n", .{});
  420. print("= {b:0>4} <- INCORRECT! THE EXPECTED OUTPUT IS {b:0>4}\n", .{ answer, expected });
  421. print("*************************************************************\n", .{});
  422. } else {
  423. print("= {b:0>4}", .{answer});
  424. }
  425. newline();
  426. }