110_quiz9.zig 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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. //
  70. // Let's first take a look at toggling bits.
  71. //
  72. // ------------------------------------------------------------------------
  73. // Toggling bits with XOR:
  74. // ------------------------------------------------------------------------
  75. // XOR stands for "exclusive or". We can toggle bits with the ^ (XOR)
  76. // bitwise operator, like so:
  77. //
  78. //
  79. // In order to output a 1, the logic of an XOR operation requires that the
  80. // two input bits are of different values. Therefore, 0 ^ 1 and 1 ^ 0 will
  81. // both yield a 1 but 0 ^ 0 and 1 ^ 1 will output 0. XOR's unique behavior
  82. // of outputing a 0 when both inputs are 1s is what makes it different from
  83. // the OR operator; it also gives us the ability to toggle bits by putting
  84. // 1s into our bitmask.
  85. //
  86. // - 1s in our bitmask operand, can be thought of as causing the
  87. // corresponding bits in the other operand to flip to the opposite value.
  88. // - 0s cause no change.
  89. //
  90. // The 0s in our bitmask preserve these values
  91. // -XOR op- ---expanded--- in the output.
  92. // _______________/
  93. // / /
  94. // 0110 1 1 0 0
  95. // ^ 1111 0 1 0 1 (bitmask)
  96. // ------ - - - -
  97. // = 1001 1 0 0 1 <- This bit was already cleared.
  98. // \_______\
  99. // \
  100. // We can think of these bits having flipped
  101. // because of the presence of 1s in those columns
  102. // of our bitmask.
  103. print("Toggle pins with XOR on PORTB\n", .{});
  104. print("-----------------------------\n", .{});
  105. PORTB = 0b1100;
  106. print(" {b:0>4} // (initial state of PORTB)\n", .{PORTB});
  107. print("^ {b:0>4} // (bitmask)\n", .{0b0101});
  108. PORTB ^= (1 << 1) | (1 << 0); // What's wrong here?
  109. checkAnswer(0b1001, PORTB);
  110. newline();
  111. PORTB = 0b1100;
  112. print(" {b:0>4} // (initial state of PORTB)\n", .{PORTB});
  113. print("^ {b:0>4} // (bitmask)\n", .{0b0011});
  114. PORTB ^= (1 << 1) & (1 << 0); // What's wrong here?
  115. checkAnswer(0b1111, PORTB);
  116. newline();
  117. // Now let's take a look at setting bits with the | operator.
  118. //
  119. // ------------------------------------------------------------------------
  120. // Setting bits with OR:
  121. // ------------------------------------------------------------------------
  122. // We can set bits on PORTB with the | (OR) operator, like so:
  123. //
  124. // var PORTB: u4 = 0b1001;
  125. // PORTB = PORTB | 0b0010;
  126. // print("PORTB: {b:0>4}\n", .{PORTB}); // output: 1011
  127. //
  128. // -OR op- ---expanded---
  129. // _ Set only this bit.
  130. // /
  131. // 1001 1 0 0 1
  132. // | 0010 0 0 1 0 (bit mask)
  133. // ------ - - - -
  134. // = 1011 1 0 1 1
  135. // \___\_______\
  136. // \
  137. // These bits remain untouched because OR-ing with
  138. // a 0 effects no change.
  139. //
  140. // ------------------------------------------------------------------------
  141. // To create a bit mask like 0b0010 used above:
  142. //
  143. // 1. First, shift the value 1 over one place with the bitwise << (shift
  144. // left) operator as indicated below:
  145. // 1 << 0 -> 0001
  146. // 1 << 1 -> 0010 <-- Shift 1 one place to the left
  147. // 1 << 2 -> 0100
  148. // 1 << 3 -> 1000
  149. //
  150. // This allows us to rewrite the above code like this:
  151. //
  152. // var PORTB: u4 = 0b1001;
  153. // PORTB = PORTB | (1 << 1);
  154. // print("PORTB: {b:0>4}\n", .{PORTB}); // output: 1011
  155. //
  156. // Finally, as in the C language, Zig allows us to use the |= operator, so
  157. // we can rewrite our code again in an even more compact and idiomatic
  158. // form: PORTB |= (1 << 1)
  159. print("Set pins with OR on PORTB\n", .{});
  160. print("-------------------------\n", .{});
  161. PORTB = 0b1001; // reset PORTB
  162. print(" {b:0>4} // (initial state of PORTB)\n", .{PORTB});
  163. print("| {b:0>4} // (bitmask)\n", .{0b0100});
  164. PORTB = PORTB ??? (1 << 2); // What's missing here?
  165. checkAnswer(0b1101, PORTB);
  166. newline();
  167. PORTB = 0b1001; // reset PORTB
  168. print(" {b:0>4} // (reset state)\n", .{PORTB});
  169. print("| {b:0>4} // (bitmask)\n", .{0b0100});
  170. PORTB ??? (1 << 2); // What's missing here?
  171. checkAnswer(0b1101, PORTB);
  172. newline();
  173. // So now we've covered how to toggle and set bits. What about clearing
  174. // them? Well, this is where Zig throws us a curve ball. Don't worry we'll
  175. // go through it step by step.
  176. // ------------------------------------------------------------------------
  177. // Clearing bits with AND and NOT:
  178. // ------------------------------------------------------------------------
  179. // We can clear bits with the & (AND) bitwise operator, like so:
  180. // PORTB = 0b1110; // reset PORTB
  181. // PORTB = PORTB & 0b1011;
  182. // print("PORTB: {b:0>4}\n", .{PORTB}); // output -> 1010
  183. //
  184. // - 0s clear bits when used in conjuction with a bitwise AND.
  185. // - 1s do nothing, thus preserving the original bits.
  186. //
  187. // -AND op- ---expanded---
  188. // __________ Clear only this bit.
  189. // /
  190. // 1110 1 1 1 0
  191. // & 1011 1 0 1 1 (bit mask)
  192. // ------ - - - -
  193. // = 1010 1 0 1 0 <- This bit was already cleared.
  194. // \_______\
  195. // \
  196. // These bits remain untouched because AND-ing with a
  197. // 1 preserves the original bit value whether 0 or 1.
  198. //
  199. // ------------------------------------------------------------------------
  200. // We can use the ~ (NOT) operator to easily create a bit mask like 1011:
  201. //
  202. // 1. First, shift the value 1 over two places with the bit-wise << (shift
  203. // left) operator as indicated below:
  204. // 1 << 0 -> 0001
  205. // 1 << 1 -> 0010
  206. // 1 << 2 -> 0100 <- The 1 has been shifted two places to the left
  207. // 1 << 3 -> 1000
  208. //
  209. // 2. The second step in creating our bit mask is to invert the bits
  210. // ~0100 -> 1011
  211. // in C we would write this as:
  212. // ~(1 << 2) -> 1011
  213. //
  214. // But if we try to compile ~(1 << 2) in Zig, we'll get an error:
  215. // unable to perform binary not operation on type 'comptime_int'
  216. //
  217. // Before Zig can invert our bits, it needs to know the number of
  218. // bits it's being asked to invert.
  219. //
  220. // We do this with the @as (cast as) built-in like this:
  221. // @as(u4, 1 << 2) -> 0100
  222. //
  223. // Finally, we can invert our new mask by placing the NOT ~ operator
  224. // before our expression, like this:
  225. // ~@as(u4, 1 << 2) -> 1011
  226. //
  227. // If you are offput by the fact that you can't simply invert bits like
  228. // you can in languages such as C without casting to a particular size
  229. // of integer, you're not alone. However, this is actually another
  230. // instance where Zig is really helpful because it protects you from
  231. // difficult to debug integer overflow bugs that can have you tearing
  232. // your hair out. In the interest of keeping things sane, Zig requires
  233. // you simply to tell it the size of number you are inverting. In the
  234. // words of Andrew Kelley, "If you want to invert the bits of an
  235. // integer, zig has to know how many bits there are."
  236. //
  237. // For more insight into the Zig team's position on why the language
  238. // takes the approach it does with the ~ operator, take a look at
  239. // Andrew's comments on the following github issue:
  240. // https://github.com/ziglang/zig/issues/1382#issuecomment-414459529
  241. //
  242. // Whew, so after all that what we end up with is:
  243. // PORTB = PORTB & ~@as(u4, 1 << 2);
  244. //
  245. // We can shorten this with the &= combined AND and assignment operator,
  246. // which applies the AND operator on PORTB and then reassigns PORTB. Here's
  247. // what that looks like:
  248. // PORTB &= ~@as(u4, 1 << 2);
  249. //
  250. print("Clear pins with AND and NOT on PORTB\n", .{});
  251. print("------------------------------------\n", .{});
  252. PORTB = 0b1110; // reset PORTB
  253. print(" {b:0>4} // (initial state of PORTB)\n", .{PORTB});
  254. print("& {b:0>4} // (bitmask)\n", .{0b1011});
  255. PORTB = PORTB & ???@as(u4, 1 << 2); // What character is missing here?
  256. checkAnswer(0b1010, PORTB);
  257. newline();
  258. PORTB = 0b0111; // reset PORTB
  259. print(" {b:0>4} // (reset state)\n", .{PORTB});
  260. print("& {b:0>4} // (bitmask)\n", .{0b1110});
  261. PORTB &= ~(1 << 0); // What's missing here?
  262. checkAnswer(0b0110, PORTB);
  263. newline();
  264. newline();
  265. // ------------------------------------------------------------------------
  266. // Conclusion
  267. // ------------------------------------------------------------------------
  268. //
  269. // While the examples in this exercise have used only 4-bit wide variables,
  270. // working with 8 bits is no different. Here's a an example where we set
  271. // every other bit beginning with the two's place:
  272. // var PORTD: u8 = 0b0000_0000;
  273. // print("PORTD: {b:0>8}\n", .{PORTD});
  274. // PORTD |= (1 << 1);
  275. // PORTD = setBit(u8, PORTD, 3);
  276. // PORTD |= (1 << 5) | (1 << 7);
  277. // print("PORTD: {b:0>8} // set every other bit\n", .{PORTD});
  278. // PORTD = ~PORTD;
  279. // print("PORTD: {b:0>8} // bits flipped with NOT (~)\n", .{PORTD});
  280. // newline();
  281. //
  282. // // Here we clear every other bit beginning with the two's place.
  283. //
  284. // PORTD = 0b1111_1111;
  285. // print("PORTD: {b:0>8}\n", .{PORTD});
  286. // PORTD &= ~@as(u8, 1 << 1);
  287. // PORTD = clearBit(u8, PORTD, 3);
  288. // PORTD &= ~@as(u8, (1 << 5) | (1 << 7));
  289. // print("PORTD: {b:0>8} // clear every other bit\n", .{PORTD});
  290. // PORTD = ~PORTD;
  291. // print("PORTD: {b:0>8} // bits flipped with NOT (~)\n", .{PORTD});
  292. // newline();
  293. }
  294. // ----------------------------------------------------------------------------
  295. // Here are some helper functions for manipulating bits
  296. // ----------------------------------------------------------------------------
  297. // Functions for setting, clearing, and toggling a single bit
  298. fn setBit(comptime T: type, byte: T, comptime bit_pos: T) !T {
  299. return byte | (1 << bit_pos);
  300. }
  301. test "setBit" {
  302. try testing.expectEqual(setBit(u8, 0b0000_0000, 3), 0b0000_1000);
  303. }
  304. fn clearBit(comptime T: type, byte: T, comptime bit_pos: T) T {
  305. return byte & ~@as(T, (1 << bit_pos));
  306. }
  307. test "clearBit" {
  308. try testing.expectEqual(clearBit(u8, 0b1111_1111, 0), 0b1111_1110);
  309. }
  310. fn toggleBit(comptime T: type, byte: T, comptime bit_pos: T) T {
  311. return byte ^ (1 << bit_pos);
  312. }
  313. test "toggleBit" {
  314. var byte = toggleBit(u8, 0b0000_0000, 0);
  315. try testing.expectEqual(byte, 0b0000_0001);
  316. byte = toggleBit(u8, byte, 0);
  317. try testing.expectEqual(byte, 0b0000_0000);
  318. }
  319. // ----------------------------------------------------------------------------
  320. // Some additional functions for setting, clearing, and toggling multiple bits
  321. // at once with a tuple because, hey, why not?
  322. // ----------------------------------------------------------------------------
  323. //
  324. fn createBitmask(comptime T: type, comptime bits: anytype) !T {
  325. comptime var bitmask: T = 0;
  326. inline for (bits) |bit| {
  327. if (bit >= @bitSizeOf(T)) return error.BitPosTooLarge;
  328. if (bit < 0) return error.BitPosTooSmall;
  329. bitmask |= (1 << bit);
  330. }
  331. return bitmask;
  332. }
  333. test "creating bitmasks from a tuple" {
  334. try testing.expectEqual(createBitmask(u8, .{0}), 0b0000_0001);
  335. try testing.expectEqual(createBitmask(u8, .{1}), 0b0000_0010);
  336. try testing.expectEqual(createBitmask(u8, .{2}), 0b0000_0100);
  337. try testing.expectEqual(createBitmask(u8, .{3}), 0b0000_1000);
  338. //
  339. try testing.expectEqual(createBitmask(u8, .{ 0, 4 }), 0b0001_0001);
  340. try testing.expectEqual(createBitmask(u8, .{ 1, 5 }), 0b0010_0010);
  341. try testing.expectEqual(createBitmask(u8, .{ 2, 6 }), 0b0100_0100);
  342. try testing.expectEqual(createBitmask(u8, .{ 3, 7 }), 0b1000_1000);
  343. try testing.expectError(error.BitPosTooLarge, createBitmask(u4, .{4}));
  344. }
  345. fn setBits(byte: u8, bits: anytype) !u8 {
  346. const bitmask = try createBitmask(u8, bits);
  347. return byte | bitmask;
  348. }
  349. test "setBits" {
  350. try testing.expectEqual(setBits(0b0000_0000, .{0}), 0b0000_0001);
  351. try testing.expectEqual(setBits(0b0000_0000, .{7}), 0b1000_0000);
  352. try testing.expectEqual(setBits(0b0000_0000, .{ 0, 1, 2, 3, 4, 5, 6, 7 }), 0b1111_1111);
  353. try testing.expectEqual(setBits(0b1111_1111, .{ 0, 1, 2, 3, 4, 5, 6, 7 }), 0b1111_1111);
  354. try testing.expectEqual(setBits(0b0000_0000, .{ 2, 3, 4, 5 }), 0b0011_1100);
  355. try testing.expectError(error.BitPosTooLarge, setBits(0b1111_1111, .{8}));
  356. try testing.expectError(error.BitPosTooSmall, setBits(0b1111_1111, .{-1}));
  357. }
  358. fn clearBits(comptime byte: u8, comptime bits: anytype) !u8 {
  359. const bitmask: u8 = try createBitmask(u8, bits);
  360. return byte & ~@as(u8, bitmask);
  361. }
  362. test "clearBits" {
  363. try testing.expectEqual(clearBits(0b1111_1111, .{0}), 0b1111_1110);
  364. try testing.expectEqual(clearBits(0b1111_1111, .{7}), 0b0111_1111);
  365. try testing.expectEqual(clearBits(0b1111_1111, .{ 0, 1, 2, 3, 4, 5, 6, 7 }), 0b000_0000);
  366. try testing.expectEqual(clearBits(0b0000_0000, .{ 0, 1, 2, 3, 4, 5, 6, 7 }), 0b000_0000);
  367. try testing.expectEqual(clearBits(0b1111_1111, .{ 0, 1, 6, 7 }), 0b0011_1100);
  368. try testing.expectError(error.BitPosTooLarge, clearBits(0b1111_1111, .{8}));
  369. try testing.expectError(error.BitPosTooSmall, clearBits(0b1111_1111, .{-1}));
  370. }
  371. fn toggleBits(comptime byte: u8, comptime bits: anytype) !u8 {
  372. const bitmask = try createBitmask(u8, bits);
  373. return byte ^ bitmask;
  374. }
  375. test "toggleBits" {
  376. try testing.expectEqual(toggleBits(0b0000_0000, .{0}), 0b0000_0001);
  377. try testing.expectEqual(toggleBits(0b0000_0000, .{7}), 0b1000_0000);
  378. try testing.expectEqual(toggleBits(0b1111_1111, .{ 0, 1, 2, 3, 4, 5, 6, 7 }), 0b000_0000);
  379. try testing.expectEqual(toggleBits(0b0000_0000, .{ 0, 1, 2, 3, 4, 5, 6, 7 }), 0b1111_1111);
  380. try testing.expectEqual(toggleBits(0b0000_1111, .{ 0, 1, 2, 3, 4, 5, 6, 7 }), 0b1111_0000);
  381. try testing.expectEqual(toggleBits(0b0000_1111, .{ 0, 1, 2, 3 }), 0b0000_0000);
  382. try testing.expectEqual(toggleBits(0b0000_0000, .{ 0, 2, 4, 6 }), 0b0101_0101);
  383. try testing.expectError(error.BitPosTooLarge, toggleBits(0b1111_1111, .{8}));
  384. try testing.expectError(error.BitPosTooSmall, toggleBits(0b1111_1111, .{-1}));
  385. }
  386. // ----------------------------------------------------------------------------
  387. // Utility functions
  388. // ----------------------------------------------------------------------------
  389. fn newline() void {
  390. print("\n", .{});
  391. }
  392. fn checkAnswer(expected: u4, answer: u4) void {
  393. if (expected != answer) {
  394. print("*************************************************************\n", .{});
  395. print("= {b:0>4} <- INCORRECT! THE EXPECTED OUTPUT IS {b:0>4}\n", .{ answer, expected });
  396. print("*************************************************************\n", .{});
  397. } else {
  398. print("= {b:0>4}", .{answer});
  399. }
  400. newline();
  401. }