110_quiz9.zig 19 KB

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