├── .circleci ├── config.yml ├── hex_auth.expect └── hex_publish.expect ├── .gitignore ├── LICENSE.txt ├── README.md ├── config ├── config.exs ├── dev.exs ├── prod.exs └── test.exs ├── lib ├── ex_lcd.ex └── ex_lcd │ ├── driver.ex │ ├── hd44780.ex │ └── io.ex ├── mix.exs ├── mix.lock └── test ├── ex_lcd └── hd44780_test.exs ├── ex_lcd_test.exs ├── support └── mock_hd44780.ex └── test_helper.exs /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | jobs: 3 | build: 4 | docker: 5 | - image: cthree87/docker-elixir-ci:latest 6 | 7 | working_directory: ~/ex_lcd 8 | 9 | steps: 10 | - checkout 11 | - run: mix local.hex --force 12 | - run: mix local.rebar --force 13 | - run: mix deps.get 14 | - run: mix deps.compile 15 | 16 | # Run tests 17 | - run: 18 | environment: 19 | MIX_ENV: "test" 20 | command: | 21 | mix test 22 | 23 | deploy_hex: 24 | docker: 25 | - image: cthree87/docker-elixir-ci:latest 26 | 27 | working_directory: ~/ex_lcd_deploy 28 | 29 | steps: 30 | - checkout 31 | - run: mix local.hex --force 32 | - run: mix local.rebar --force 33 | - run: mix deps.get 34 | - run: mix deps.compile 35 | 36 | # Deploy to Hex 37 | - deploy: 38 | command: | 39 | if [ ${CIRCLE_BRANCH} == "master" ]; then 40 | # Hex authentication expect script 41 | expect .circleci/hex_auth.expect 42 | # Publish the new release to hex 43 | expect .circleci/hex_publish.expect 44 | fi 45 | -------------------------------------------------------------------------------- /.circleci/hex_auth.expect: -------------------------------------------------------------------------------- 1 | #!/usr/bin/expect 2 | 3 | set timeout 9 4 | set hex_user "$env(HEX_USER)" 5 | set hex_password "$env(HEX_PW)" 6 | log_user 0 7 | 8 | spawn mix hex.user auth 9 | 10 | expect { 11 | timeout { send_user "\n Failed authenticating with hex\n"; exit 1 } 12 | "Username:" 13 | } 14 | 15 | send "$hex_user\r" 16 | 17 | expect { 18 | "Password:" 19 | } 20 | 21 | send "$hex_password\r" 22 | 23 | expect { 24 | "*API key with user password..." 25 | } 26 | 27 | send_user "\nSuccessfully Authenticated.\n" 28 | 29 | wait 30 | close 31 | -------------------------------------------------------------------------------- /.circleci/hex_publish.expect: -------------------------------------------------------------------------------- 1 | #!/usr/bin/expect 2 | 3 | set timeout 9 4 | set hex_password "$env(HEX_PW)" 5 | log_user 0 6 | 7 | spawn mix hex.publish 8 | 9 | expect { 10 | "Password:" 11 | } 12 | 13 | send "$hex_password\r" 14 | 15 | log_user 1 16 | 17 | expect { 18 | "*[Yn]?" 19 | } 20 | 21 | send "Y\r" 22 | 23 | wait 24 | close 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | _build/ 2 | cover/ 3 | deps/ 4 | doc/ 5 | erl_crash.dump 6 | *.ez 7 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ExLCD 2 | 3 | [![Hex.pm](https://img.shields.io/hexpm/v/ex_lcd.svg)](https://hex.pm/packages/ex_lcd) 4 | [![Hex.pm](https://img.shields.io/hexpm/dt/ex_lcd.svg)](https://hex.pm/packages/ex_lcd) 5 | [![Hex.pm](https://img.shields.io/hexpm/l/ex_lcd.svg)](https://hex.pm/packages/ex_lcd) 6 | 7 | **ExLCD** is a Hex package providing an API and support for character matrix LCD displays in your Elixir and nerves projects. It uses [elixir_ale](https://github.com/fhunleth/elixir_ale) for hardware IO. 8 | 9 | The hardware interface and the user API are separate modules providing relative hardware independence. This provides you with the ability to change displays without significant changes your application code. 10 | 11 | **Disclaimer:** This is still under heavy development and probably isn't suited for production use. Please consider testing and contributing to improving the project. 12 | 13 | ## Documentation 14 | 15 | Project and API documentation is available online at [hexdocs.pm](https://hexdocs.pm/ex_lcd/) 16 | 17 | ## Examples 18 | 19 | Example applications using ExLCD are available in the [cthree/ex_lcd_examples](https://github.com/cthree/ex_lcd_examples) Github repository. 20 | 21 | ## Contributing 22 | 23 | If you wish to support a new type of display module, fix or report a bug, add a feature or otherwise contribute to the project please [open an issue](https://github.com/cthree/ex_lcd/issues) to discuss your issue or idea. I'm happy to accept suggestions, bug reports, pull requests and other help. Driver modules for unsupported displays is especially appreciated. 24 | 25 | ## Acknowledgements 26 | 27 | Many thanks to [@tmecklem](https://github.com/tmecklem) for inspiration and encouragement. ExLCD started as his **elixir_lcd** package. 28 | 29 | ## License 30 | 31 | Licensed under the [Apache-2.0](https://choosealicense.com/licenses/apache-2.0/) license. Please see the [LICENSE file](https://github.com/cthree/ex_lcd/blob/master/LICENSE.txt) included in the repository if you are unfamiliar with the terms and conditions. 32 | 33 | ## Installation 34 | 35 | **ExLCD** [is available in Hex](https://hex.pm/docs/publish), the package can be installed as a dependency of your project: 36 | 37 | 1. Add **ex_lcd** to your list of dependencies in `mix.exs`: 38 | ```elixir 39 | def deps do 40 | [{:ex_lcd, "~> 0.4.0"}] 41 | end 42 | ``` 43 | 44 | 2. Ensure **ex_lcd** is started before your application: 45 | ```elixir 46 | def application(_target) do 47 | [mod: {MyApplication.Application, []}, 48 | extra_applications: [:ex_lcd]] 49 | end 50 | ``` 51 | -------------------------------------------------------------------------------- /config/config.exs: -------------------------------------------------------------------------------- 1 | use Mix.Config 2 | 3 | # Sample HD44780 configuration for a 2x20 display connected to 4 | # my Raspberry Pi0W. The 4 bit interface requires 6 GPIO pins 5 | # which are managed by the driver: 6 | # 7 | # config :ex_lcd, lcd: %{ 8 | # rs: 25, 9 | # en: 24, 10 | # d4: 23, 11 | # d5: 22, 12 | # d6: 18, 13 | # d7: 17, 14 | # rows: 2, 15 | # cols: 20, 16 | # font_5x10: false 17 | # } 18 | 19 | import_config "#{Mix.env}.exs" 20 | -------------------------------------------------------------------------------- /config/dev.exs: -------------------------------------------------------------------------------- 1 | use Mix.Config 2 | 3 | config :ex_lcd, :gpio, ExLCD.GPIO 4 | config :ex_lcd, :i2c, ExLCD.I2C 5 | config :ex_lcd, :spi, ExLCD.SPI 6 | -------------------------------------------------------------------------------- /config/prod.exs: -------------------------------------------------------------------------------- 1 | use Mix.Config 2 | -------------------------------------------------------------------------------- /config/test.exs: -------------------------------------------------------------------------------- 1 | use Mix.Config 2 | 3 | config :ex_lcd, :gpio, ExLCD.GPIO 4 | config :ex_lcd, :i2c, ExLCD.I2C 5 | config :ex_lcd, :spi, ExLCD.SPI 6 | -------------------------------------------------------------------------------- /lib/ex_lcd.ex: -------------------------------------------------------------------------------- 1 | defmodule ExLCD do 2 | @moduledoc """ 3 | **ExLCD** implements a standard API for controlling and 4 | displaying text on character matrix LCD display modules. ExLCD 5 | handles most modes and operations supported by common display modules. 6 | 7 | ExLCD controls an assortment of displays by interacting with a 8 | driver module implementing the ExLCD.Driver behaviour. 9 | ExLCD has no direct support for controlling hardware and instead 10 | delegates low-level functions driver modules for the actual device. 11 | 12 | ## Usage 13 | 14 | ExLCD is implemented as a GenServer. Start it by calling 15 | ExLCD.start_link/1 and passing a tuple containing the 16 | name of the driver module in the first element and a map of 17 | configuration parameters in second element. See the driver module 18 | documentation for what configuration parameters it accepts. 19 | 20 | Example: 21 | ```elixir 22 | alias ExLCD 23 | ExLCD.start_link({ExLCD.HD44780, %{...}}) 24 | ``` 25 | """ 26 | use GenServer 27 | 28 | @type feature :: :display | :cursor | :blink | :autoscroll | 29 | :rtl_text | :ltr_text 30 | @type bitmap :: list 31 | 32 | defmodule LCDState do 33 | defstruct driver: nil, config: nil, display: nil, callback: nil 34 | end 35 | 36 | @doc """ 37 | Start the ExLCD GenServer to manage the display. 38 | 39 | Pass a tuple containing the name of the driver module in the first element 40 | and a map of configuration parameters in second element. See the driver 41 | module documentation for what configuration parameters it accepts. 42 | 43 | Example: 44 | ```elixir 45 | alias ExLCD 46 | ExLCD.start_link({ExLCD.HD44780, %{...}}) 47 | ``` 48 | """ 49 | @spec start_link({term, map}) :: {:ok, pid} 50 | def start_link({driver_module, config}) do 51 | state = %LCDState{driver: driver_module, config: config} 52 | GenServer.start_link(__MODULE__, state, name: __MODULE__) 53 | end 54 | 55 | @doc false 56 | @spec init(term) :: {:ok, term} 57 | def init(state) do 58 | state = %LCDState{state | display: apply(state.driver, :start, [state.config])} 59 | state = %LCDState{state | callback: apply(state.driver, :execute, [])} 60 | {:ok, state} 61 | end 62 | 63 | # ------------------------------------------------------------------- 64 | # Public API 65 | # 66 | 67 | @doc """ 68 | Clear the display. 69 | 70 | Example: 71 | ```elixir 72 | iex> ExLCD.clear 73 | :ok 74 | ``` 75 | """ 76 | @spec clear() :: :ok 77 | def clear(), do: cast(:clear) 78 | 79 | @doc """ 80 | Home the cursor position to row 0, col 0 81 | 82 | Example: 83 | ```elixir 84 | iex> ExLCD.home 85 | :ok 86 | ``` 87 | """ 88 | @spec home() :: :ok 89 | def home(), do: cast(:home) 90 | 91 | @doc """ 92 | Position the cursor at a specified row and colum 93 | 94 | Example: 95 | ```elixir 96 | iex> ExLCD.move_to(2, 12) 97 | :ok 98 | ``` 99 | """ 100 | @spec move_to(row::integer, col::integer) :: :ok 101 | def move_to(row, col), do: cast({:set_cursor, row, col}) 102 | 103 | @doc """ 104 | Write a string or charlist to the display at the current cursor position. 105 | 106 | Example: 107 | ```elixir 108 | iex> ExLCD.write("ExLCD!") 109 | :ok 110 | iex> ExLCD.write('ExLCD!') 111 | :ok 112 | iex> ExLCD.write(['E', 'x', 'L', 'C', 'D', '!']) 113 | :ok 114 | ``` 115 | """ 116 | @spec write(binary | list) :: :ok 117 | def write(content) when is_binary(content) do 118 | cast({:print, content}) 119 | end 120 | def write(content), do: cast({:write, content}) 121 | 122 | @doc """ 123 | Scroll the display contents left by 1 or some number of columns. 124 | 125 | Example: 126 | ```elixir 127 | iex> ExLCD.scroll_right(6) 128 | :ok 129 | ``` 130 | """ 131 | @spec scroll_left(integer) :: :ok 132 | def scroll_left(cols \\ 1), do: cast({:scroll, -cols}) 133 | 134 | @doc """ 135 | Scroll the display contents right by 1 or some number of columns. 136 | 137 | Example: 138 | ```elixir 139 | iex> ExLCD.scroll_right(6) 140 | :ok 141 | ``` 142 | """ 143 | @spec scroll_right(integer) :: :ok 144 | def scroll_right(cols \\ 1), do: cast({:scroll, cols}) 145 | 146 | @doc """ 147 | Move the cursor 1 or some number of columns to the left of its current 148 | position. 149 | 150 | Example: 151 | ```elixir 152 | iex> ExLCD.move_left(4) 153 | :ok 154 | ``` 155 | """ 156 | @spec move_left(integer) :: :ok 157 | def move_left(cols \\ 1), do: cast({:left, cols}) 158 | 159 | @doc """ 160 | Move the cursor 1 or some number of columns to the right of its current 161 | position. 162 | 163 | Example: 164 | ```elixir 165 | iex> ExLCD.move_right(1) 166 | :ok 167 | ``` 168 | """ 169 | @spec move_right(integer) :: :ok 170 | def move_right(cols \\ 1), do: cast({:right, cols}) 171 | 172 | @doc """ 173 | Program a custom character glyph. 174 | 175 | Custom glyphs may not be supported by all displays. Check the driver 176 | to see if it is on yours. Pass a custome character index or slot 177 | number and a list of integers representing the glyph bitmap data. Format 178 | of the bitmap data and the numbering of the character slots is highly 179 | dependent on the display controller. Refer to the driver module for 180 | details. 181 | 182 | Example: 183 | ```elixir 184 | iex> ExLCD.create_char(0, [0x7F, 0x7F, 0x7F, 0x7F, 185 | ...> 0x7F, 0x7F, 0x7F, 0x7F]) 186 | :ok 187 | ``` 188 | """ 189 | @spec create_char(integer, bitmap) :: :ok 190 | def create_char(idx, bits), do: cast({:char, idx, bits}) 191 | 192 | @doc """ 193 | Enable a display feature. 194 | 195 | Example: 196 | ```elixir 197 | iex> ExLCD.enable(:display) 198 | :ok 199 | ``` 200 | """ 201 | @spec enable(feature) :: :ok 202 | def enable(:cursor), do: cast({:enable, :cursor}) 203 | def enable(:blink), do: cast({:enable, :blink}) 204 | def enable(:display), do: cast({:enable, :display}) 205 | def enable(:autoscroll), do: cast({:enable, :autoscroll}) 206 | def enable(:rtl_text), do: cast({:enable, :rtl_text}) 207 | def enable(:ltr_text), do: cast({:enable, :ltr_text}) 208 | 209 | @doc """ 210 | Disable a display feature. 211 | 212 | Example: 213 | ```elixir 214 | iex> ExLCD.disable(:blink) 215 | :ok 216 | ``` 217 | """ 218 | @spec disable(feature) :: :ok 219 | def disable(:cursor), do: cast({:disable, :cursor}) 220 | def disable(:blink), do: cast({:disable, :blink}) 221 | def disable(:display), do: cast({:disable, :display}) 222 | def disable(:autoscroll), do: cast({:disable, :autoscroll}) 223 | def disable(:rtl_text), do: ExLCD.enable(:ltr_text) 224 | def disable(:ltr_text), do: ExLCD.enable(:rtl_text) 225 | 226 | @doc """ 227 | Stop the driver and release hardware resources. 228 | 229 | Example: 230 | ```elixir 231 | iex> ExLCD.stop 232 | :ok 233 | ``` 234 | """ 235 | @spec stop() :: :ok 236 | def stop(), do: stop(:shutdown) 237 | 238 | # ------------------------------------------------------------------- 239 | # GenServer Cast callbacks 240 | # 241 | @doc false 242 | def handle_cast(:clear, state), do: execute({:clear, []}, state) 243 | def handle_cast(:home, state), do: execute({:home, []}, state) 244 | def handle_cast({:set_cursor, row, col}, state) do 245 | execute({:set_cursor, {row, col}}, state) 246 | end 247 | def handle_cast({:print, content}, state) do 248 | execute({:print, content}, state) 249 | end 250 | def handle_cast({:write, content}, state) do 251 | execute({:write, content}, state) 252 | end 253 | def handle_cast({:scroll, cols}, state) do 254 | execute({:scroll, cols}, state) 255 | end 256 | def handle_cast({:right, cols}, state) do 257 | execute({:right, cols}, state) 258 | end 259 | def handle_cast({:left, cols}, state) do 260 | execute({:left, cols}, state) 261 | end 262 | def handle_cast({:char, idx, bitmap}, state) when idx in 0..7 and length(bitmap) === 8 do 263 | execute({:char, idx, bitmap}, state) 264 | end 265 | def handle_cast({:enable, feature}, state) do 266 | execute({feature, :on}, state) 267 | end 268 | def handle_cast({:disable, feature}, state) do 269 | execute({feature, :off}, state) 270 | end 271 | 272 | defp execute(op, state) do 273 | {_result, display} = state.callback.(state.display, op) 274 | {:noreply, updated_display_state(state, display)} 275 | end 276 | 277 | # ------------------------------------------------------------------- 278 | # Private Utility Functions 279 | # 280 | 281 | defp cast(msg), do: GenServer.cast(__MODULE__, msg) 282 | 283 | defp stop(msg), do: GenServer.stop(__MODULE__, msg) 284 | 285 | defp updated_display_state(state, display) do 286 | %LCDState{state | display: display} 287 | end 288 | end 289 | -------------------------------------------------------------------------------- /lib/ex_lcd/driver.ex: -------------------------------------------------------------------------------- 1 | defmodule ExLCD.Driver do 2 | @moduledoc """ 3 | ExLCD.Driver defines the behaviour expected of display driver 4 | modules. Each display driver module must use this module and implement the 5 | expected callback functions. 6 | 7 | ```elixir 8 | defmodule MyDisplayDriver do 9 | use ExLCD.Driver 10 | ... 11 | end 12 | ``` 13 | """ 14 | @doc false 15 | defmacro __using__(_) do 16 | quote do 17 | import Kernel, except: [defp: 2] 18 | import unquote(__MODULE__), only: [defp: 2, target: 0] 19 | @behaviour ExLCD.Driver 20 | end 21 | end 22 | 23 | # Redefine defp when testing to expose private functions 24 | @doc false 25 | defmacro defp(definition, do: body) do 26 | case Mix.env do 27 | :test -> quote do 28 | Kernel.def(unquote(definition)) do 29 | unquote(body) 30 | end 31 | end 32 | _ -> quote do 33 | Kernel.defp(unquote(definition)) do 34 | unquote(body) 35 | end 36 | end 37 | end 38 | end 39 | 40 | @doc false 41 | # Return the nerves build target or "host" if there isn't one 42 | def target() do 43 | System.get_env("MIX_TARGET") || "host" 44 | end 45 | 46 | @typedoc """ 47 | Opaque driver module state data 48 | """ 49 | @type display :: map 50 | 51 | @doc """ 52 | start/1 is called during initialization of ExLCD which passes 53 | a map of configuration parameters for the driver. The driver is_ 54 | expected to initialize the display to a ready state and return 55 | state data held by and passed into the driver on each call. ExLCD 56 | manages your driver's state. After this callback returns it is expected 57 | that the display is ready to process commands from ExLCD. 58 | """ 59 | @callback start(map) :: {:ok | :error, display} 60 | 61 | @doc """ 62 | stop/1 may be called on request by the application to free the hardware 63 | resources held by the display driver. 64 | """ 65 | @callback stop(display) :: :ok 66 | 67 | @doc """ 68 | execute/0 is called by ExLCD to learn the function it should call 69 | to send commands to your driver. The typespec of the function returned 70 | must be: 71 | function(display, operation) :: display 72 | The returned function will be called upon to do all of the heavy lifting. 73 | """ 74 | @callback execute :: function 75 | end 76 | -------------------------------------------------------------------------------- /lib/ex_lcd/hd44780.ex: -------------------------------------------------------------------------------- 1 | defmodule ExLCD.HD44780 do 2 | @moduledoc """ 3 | **ExLCD.HD44780** is the display driver module for Hitachi 4 | HD44780 type parallel LCD display controller managed display modules. 5 | 6 | ## Hitachi HD44780 Style Controller (including Sitronix ST7066) 7 | 8 | The HD44780 is the most ubiquitous character matrix display controller 9 | but not the only one. It supports a number of standard operations like 10 | moving the cursor, displaying characters and scrolling. It is an 8-bit 11 | parallel interface which can operate in 4-bit mode by sending 2 4-bit 12 | nibbles to make one 8-bit byte. 13 | 14 | It supports 208 characters which are compatible with UNICODE single byte 15 | latin characters. The controller character ROM includes a number of non- 16 | standard character glyphs which this driver maps to their multi-byte 17 | UNICODE equivilents automatically. See the character map in this file for 18 | details. There are also 8 user definable character bitmaps mapped to 19 | characters byte codes 0-7. 20 | 21 | ## Configuration 22 | 23 | The start/1 function expects to receive a map of configuration settings 24 | for the display and it's hardware interface. The configuration map is 25 | passed by your application to ExLCD.start_link/1 and then on to this 26 | driver module. Please see ExLCD for details. The following keys are 27 | used by this driver to operate the display: 28 | 29 | * *Key* -> **Type(O|R)** -> *Description* 30 | * rs -> integer(R) -> The GPIO pin ID for the RS signal 31 | * en -> integer(R) -> The GPIO pin ID for the EN signal 32 | * d0 -> integer(O) -> The GPIO pin ID for the d0 signal 33 | * d1 -> integer(O) -> The GPIO pin ID for the d1 signal 34 | * d2 -> integer(O) -> The GPIO pin ID for the d2 signal 35 | * d3 -> integer(O) -> The GPIO pin ID for the d3 signal 36 | * d4 -> integer(R) -> The GPIO pin ID for the d4 signal 37 | * d5 -> integer(R) -> The GPIO pin ID for the d5 signal 38 | * d6 -> integer(R) -> The GPIO pin ID for the d6 signal 39 | * d7 -> integer(R) -> The GPIO pin ID for the d7 signal 40 | * rows -> integer(R) -> The number of display rows or lines 41 | * cols -> integer(R) -> The number of display columns 42 | * font_5x10 -> boolean(O) -> Font: true: 5x10, false: 5x8 (default) 43 | 44 | O - optional 45 | R - required 46 | 47 | Example: 48 | 49 | ```elixir 50 | config :MyApp, hd44780: %{ 51 | rs: 1, 52 | en: 2, 53 | d4: 3, 54 | d5: 4, 55 | d6: 5, 56 | d7: 6, 57 | rows: 2, 58 | cols: 20 59 | } 60 | ``` 61 | 62 | ## More Information 63 | 64 | For more information about your display and its capabilities here are 65 | a few resources to help you get the most of it: 66 | 67 | * Hitachi HD44780 Datasheet 68 | * Wikipedia Entry for HD44780 69 | * ExLCD 70 | * Raspberry Pi Example Application with nerves 71 | """ 72 | 73 | use Bitwise 74 | use ExLCD.Driver 75 | use ExLCD.IO 76 | 77 | @low 0 78 | @high 1 79 | 80 | # Function set flags 81 | @mode_4bit 0x01 82 | @mode_8bit 0x00 83 | @font_5x8 0x00 84 | @font_5x10 0x04 85 | @lines_1 0x00 86 | @lines_2 0x08 87 | 88 | # Command flags 89 | @cmd_clear 0x01 90 | @cmd_home 0x02 91 | @cmd_entrymodeset 0x04 92 | @cmd_dispcontrol 0x08 93 | @cmd_cursorshift 0x10 94 | @cmd_functionset 0x20 95 | @cmd_setcgramaddr 0x40 96 | @cmd_setddramaddr 0x80 97 | 98 | # Entry mode flags 99 | @entry_left 0x02 100 | @entry_increment 0x01 101 | 102 | # Display control flags 103 | @ctl_display 0x04 104 | @ctl_cursor 0x02 105 | @ctl_blink 0x01 106 | 107 | # Shift flags 108 | @shift_display 0x08 109 | @shift_right 0x04 110 | 111 | @pins_4bit [:rs, :en, :d4, :d5, :d6, :d7] 112 | @pins_8bit [:d0, :d1, :d2, :d3] 113 | 114 | # ------------------------------------------------------------------- 115 | # CharDisplay.Driver Behaviour 116 | # 117 | @doc false 118 | def start(config) do 119 | init(config) 120 | end 121 | 122 | @doc false 123 | def stop(display) do 124 | {:ok, display} = command(display, {:display, :off}) 125 | [ :rs_pid, :en_pid, 126 | :d0_pid, :d1_pid, :d2_pid, :d3_pid, 127 | :d4_pid, :d5_pid, :d6_pid, :d7_pid ] 128 | |> Enum.filter(fn x -> not is_nil(display[x]) end) 129 | |> Enum.each(fn x -> @gpio.release(display[x]) end) 130 | :ok 131 | end 132 | 133 | @doc false 134 | def execute do 135 | &command/2 136 | end 137 | 138 | # ------------------------------------------------------------------ 139 | # Initialization 140 | # 141 | 142 | defp init(config) do 143 | # validate and unpack the config 144 | config |> validate_config!() 145 | 146 | bits = case config[:d0] do 147 | nil -> @mode_4bit 148 | _ -> @mode_8bit 149 | end 150 | 151 | lines = case config.rows do 152 | 1 -> @lines_1 153 | _ -> @lines_2 154 | end 155 | 156 | font = case config[:font_5x10] do 157 | true -> @font_5x10 158 | _ -> @font_5x8 159 | end 160 | 161 | pins = case bits do 162 | @mode_8bit -> @pins_4bit ++ @pins_8bit 163 | _ -> @pins_4bit 164 | end 165 | 166 | starting_function_state = @cmd_functionset ||| bits ||| font ||| lines 167 | 168 | display = Map.merge(config, %{ 169 | function_set: starting_function_state, 170 | display_control: @cmd_dispcontrol, 171 | entry_mode: @cmd_entrymodeset, 172 | shift_control: @cmd_cursorshift 173 | }) 174 | 175 | display 176 | |> reserve_gpio_pins(pins) 177 | |> rs(@low) 178 | |> en(@low) 179 | |> poi(bits) 180 | |> set_feature(:function_set) 181 | |> clear() 182 | end 183 | 184 | # setup GPIO output pins, add the pids to the config and return 185 | defp reserve_gpio_pins(config, pins) do 186 | config 187 | |> Map.take(pins) 188 | |> Enum.map(fn {k, v} -> {String.to_atom("#{k}_pid"), start_pin(v, :output)} end) 189 | |> Map.new() 190 | |> Map.merge(config) 191 | end 192 | 193 | # start ElixirALE.GPIO GenServer to manage a GPIO pin and return the pid 194 | defp start_pin(pin, direction) do 195 | with {:ok, pid} <- @gpio.start_link(pin, direction), do: pid 196 | end 197 | 198 | # Software Power On Init (POI) for 4bit operation of HD44780 controller. 199 | # Since the display is initialized more than 50mS after > 4.7V on due to 200 | # OS/BEAM/App boot time this isn't strictly necessary but let's be 201 | # safe and do it anyway. 202 | defp poi(state, @mode_4bit) do 203 | state 204 | |> write_4_bits(0x03) 205 | |> write_4_bits(0x03) 206 | |> write_4_bits(0x03) 207 | |> write_4_bits(0x02) 208 | end 209 | 210 | # POI for 8 bit mode 211 | defp poi(state, @mode_8bit) do 212 | state 213 | |> set_feature(:function_set) 214 | |> set_feature(:function_set) 215 | |> set_feature(:function_set) 216 | end 217 | 218 | defp validate_config!(config) do 219 | config 220 | end 221 | 222 | # ------------------------------------------------------------------- 223 | # ExLCD API callback 224 | # 225 | 226 | defp command(display, {:clear, _params}) do 227 | clear(display) 228 | {:ok, display} 229 | end 230 | 231 | defp command(display, {:home, _params}) do 232 | home(display) 233 | {:ok, display} 234 | end 235 | 236 | # translate string to charlist 237 | defp command(display, {:print, content}) do 238 | characters = String.to_charlist(content) 239 | command(display, {:write, characters}) 240 | end 241 | 242 | defp command(display, {:write, content}) do 243 | content 244 | |> Enum.each(fn(x) -> write_a_byte(display, x, @high) end) 245 | {:ok, display} 246 | end 247 | 248 | defp command(display, {:set_cursor, {row, col}}) do 249 | {:ok, set_cursor(display, {row, col})} 250 | end 251 | defp command(display, {:cursor, :off}) do 252 | {:ok, disable_feature_flag(display, :display_control, @ctl_cursor)} 253 | end 254 | defp command(display, {:cursor, :on}) do 255 | {:ok, enable_feature_flag(display, :display_control, @ctl_cursor)} 256 | end 257 | defp command(display, {:blink, :off}) do 258 | {:ok, disable_feature_flag(display, :display_control, @ctl_blink)} 259 | end 260 | defp command(display, {:blink, :on}) do 261 | {:ok, enable_feature_flag(display, :display_control, @ctl_blink)} 262 | end 263 | defp command(display, {:display, :off}) do 264 | {:ok, disable_feature_flag(display, :display_control, @ctl_display)} 265 | end 266 | defp command(display, {:display, :on}) do 267 | {:ok, enable_feature_flag(display, :display_control, @ctl_display)} 268 | end 269 | defp command(display, {:autoscroll, :off}) do 270 | {:ok, disable_feature_flag(display, :entry_mode, @entry_increment)} 271 | end 272 | defp command(display, {:autoscroll, :on}) do 273 | {:ok, enable_feature_flag(display, :entry_mode, @entry_increment)} 274 | end 275 | defp command(display, {:rtl_text, :on}) do 276 | {:ok, disable_feature_flag(display, :entry_mode, @entry_left)} 277 | end 278 | defp command(display, {:ltr_text, :on}) do 279 | {:ok, enable_feature_flag(display, :entry_mode, @entry_left)} 280 | end 281 | 282 | # Scroll the entire display left (-) or right (+) 283 | defp command(display, {:scroll, 0}), do: {:ok, display} 284 | defp command(display, {:scroll, cols}) when cols < 0 do 285 | write_a_byte(display, @cmd_cursorshift ||| @shift_display) 286 | command(display, {:scroll, cols + 1}) 287 | end 288 | defp command(display, {:scroll, cols}) do 289 | write_a_byte(display, @cmd_cursorshift ||| @shift_display ||| @shift_right) 290 | command(display, {:scroll, cols - 1}) 291 | end 292 | 293 | # Scroll(move) cursor right 294 | defp command(display, {:right, 0}), do: {:ok, display} 295 | defp command(display, {:right, cols}) do 296 | write_a_byte(display, @cmd_cursorshift ||| @shift_right) 297 | command(display, {:right, cols - 1}) 298 | end 299 | 300 | # Scroll(move) cursor left 301 | defp command(display, {:left, 0}), do: {:ok, display} 302 | defp command(display, {:left, cols}) do 303 | write_a_byte(display, @cmd_cursorshift) 304 | command(display, {:left, cols - 1}) 305 | end 306 | 307 | # Program custom character to CGRAM 308 | defp command(display, {:char, idx, bitmap}) when idx in 0..7 and length(bitmap) === 8 do 309 | write_a_byte(display, @cmd_setcgramaddr ||| (idx <<< 3)) 310 | for line <- bitmap do 311 | write_a_byte(display, line, @high) 312 | end 313 | {:ok, display} 314 | end 315 | 316 | # All other commands are unsupported 317 | defp command(display, _), do: {:unsupported, display} 318 | 319 | # ------------------------------------------------------------------- 320 | # Low-level device and utility functions 321 | # 322 | 323 | defp clear(display) do 324 | display 325 | |> write_a_byte(@cmd_clear) 326 | |> delay(3_000) 327 | end 328 | 329 | defp home(display) do 330 | display 331 | |> write_a_byte(@cmd_home) 332 | |> delay(3_000) 333 | end 334 | 335 | # DDRAM is organized as two 40 byte rows. In a 2x display the first row 336 | # maps to address 0x00 - 0x27 and the second row maps to 0x40 - 0x67 337 | # in a 4x display rows 0 & 2 are mapped to the first row of DDRAM and 338 | # rows 1 & 3 map to the second row of DDRAM. This means that the rows 339 | # are not contiguous in memory. 340 | # 341 | # row_offsets/1 determines the starting DDRAM address of each display row 342 | # and returns a map for up to 4 rows. 343 | defp row_offsets(cols) do 344 | %{ 0 => 0x00, 1 => 0x40, 2 => 0x00 + cols, 3 => 0x40 + cols } 345 | end 346 | 347 | # Set the DDRAM address corresponding to the {row,col} position 348 | defp set_cursor(display, {row, col}) do 349 | col = min(col, display[:cols] - 1) 350 | row = min(row, display[:rows] - 1) 351 | %{^row => offset} = row_offsets(display[:cols]) 352 | write_a_byte(display, @cmd_setddramaddr ||| (col + offset)) 353 | end 354 | 355 | # Switch a register flag bit OFF(0). Return the updated state. 356 | defp disable_feature_flag(state, feature, flag) do 357 | %{state | feature => (state[feature] &&& ~~~flag)} 358 | |> set_feature(feature) 359 | end 360 | 361 | # Switch a register flag bit ON(1). Return the updated state. 362 | defp enable_feature_flag(state, feature, flag) do 363 | %{state | feature => (state[feature] ||| flag)} 364 | |> set_feature(feature) 365 | end 366 | 367 | # Write a feature register to the controller and return the state. 368 | defp set_feature(display, feature) do 369 | display |> write_a_byte(display[feature]) 370 | end 371 | 372 | # Write a byte to the device 373 | defp write_a_byte(display, byte_to_write, rs_value \\ @low) do 374 | display |> rs(rs_value) |> delay(1_000) 375 | 376 | case display[:d0] do 377 | nil -> display 378 | |> write_4_bits(byte_to_write >>> 4) 379 | |> write_4_bits(byte_to_write) 380 | _ -> display 381 | |> write_8_bits(byte_to_write) 382 | end 383 | end 384 | 385 | # Write 8 parallel bits to the device 386 | defp write_8_bits(display, bits) do 387 | @gpio.write(display.d0_pid, bits &&& 0x01) 388 | @gpio.write(display.d1_pid, bits >>> 1 &&& 0x01) 389 | @gpio.write(display.d2_pid, bits >>> 2 &&& 0x01) 390 | @gpio.write(display.d3_pid, bits >>> 3 &&& 0x01) 391 | @gpio.write(display.d4_pid, bits >>> 4 &&& 0x01) 392 | @gpio.write(display.d5_pid, bits >>> 5 &&& 0x01) 393 | @gpio.write(display.d6_pid, bits >>> 6 &&& 0x01) 394 | @gpio.write(display.d7_pid, bits >>> 7 &&& 0x01) 395 | pulse_en(display) 396 | end 397 | 398 | # Write 4 parallel bits to the device 399 | defp write_4_bits(display, bits) do 400 | @gpio.write(display.d4_pid, bits &&& 0x01) 401 | @gpio.write(display.d5_pid, bits >>> 1 &&& 0x01) 402 | @gpio.write(display.d6_pid, bits >>> 2 &&& 0x01) 403 | @gpio.write(display.d7_pid, bits >>> 3 &&& 0x01) 404 | pulse_en(display) 405 | end 406 | 407 | defp rs(display, value) do 408 | @gpio.write(display[:rs_pid], value) 409 | display 410 | end 411 | 412 | defp en(display, value) do 413 | @gpio.write(display[:en_pid], value) 414 | display 415 | end 416 | 417 | defp pulse_en(display) do 418 | display 419 | |> en(@low) 420 | |> en(@high) 421 | |> en(@low) 422 | end 423 | 424 | def delay(display, microseconds) do 425 | # Unfortunately, BEAM does not provides microsecond precision 426 | # And if we need waiting, we MUST wait 427 | ms = max(round(microseconds / 1000), 1) 428 | Process.sleep(ms) 429 | display 430 | end 431 | end 432 | -------------------------------------------------------------------------------- /lib/ex_lcd/io.ex: -------------------------------------------------------------------------------- 1 | defmodule ExLCD.IO do 2 | @moduledoc false 3 | 4 | defmacro __using__(_) do 5 | quote do 6 | @gpio Application.get_env(:ex_lcd, :gpio, ElixirALE.GPIO) 7 | @i2c Application.get_env(:ex_lcd, :i2c, ElixirALE.I2C) 8 | @spi Application.get_env(:ex_lcd, :spi, ElixirALE.SPI) 9 | end 10 | end 11 | end 12 | 13 | defmodule ExLCD.GPIO do 14 | @moduledoc false 15 | 16 | def start_link(pin, _pin_direction \\ :foo, _opts \\ []) do 17 | {:ok, pin} 18 | end 19 | 20 | def write(pin, value) do 21 | MockHD44780.write(pin, value) 22 | :ok 23 | end 24 | 25 | def release(_pin), do: :ok 26 | end 27 | 28 | defmodule ExLCD.I2C do 29 | @moduledoc false 30 | use GenServer 31 | 32 | end 33 | 34 | defmodule ExLCD.SPI do 35 | @moduledoc false 36 | use GenServer 37 | 38 | end 39 | -------------------------------------------------------------------------------- /mix.exs: -------------------------------------------------------------------------------- 1 | defmodule ExLCD.Mixfile do 2 | use Mix.Project 3 | 4 | def project do 5 | [app: :ex_lcd, 6 | version: "0.4.0", 7 | elixir: "~> 1.4", 8 | description: description(), 9 | package: package(), 10 | docs: [extras: ["README.md"]], 11 | aliases: ["docs": ["docs", ©_images/1]], 12 | build_embedded: Mix.env == :prod, 13 | start_permanent: Mix.env == :prod, 14 | elixirc_paths: elixirc_paths(Mix.env), 15 | deps: deps()] 16 | end 17 | 18 | # Specifies which paths to compile per environment. 19 | defp elixirc_paths(:prod), do: ["lib"] 20 | defp elixirc_paths(_), do: ["test/support", "lib"] 21 | 22 | def application do 23 | [] 24 | end 25 | 26 | defp deps do 27 | [ 28 | {:elixir_ale, "~> 0.6.1"}, 29 | {:ex_doc, "~> 0.11", only: [:dev]} 30 | ] 31 | end 32 | 33 | defp description do 34 | """ 35 | Hex package to use character matrix LCD displays including HD44780 36 | in your Elixir/nerves projects. Uses elixir_ale for IO. 37 | """ 38 | end 39 | 40 | defp package do 41 | [ 42 | files: ["lib", "mix.exs", "README*", "LICENSE*"], 43 | maintainers: ["Erik Petersen"], 44 | licenses: ["Apache-2.0"], 45 | links: %{"GitHub" => "https://github.com/cthree/ex_lcd"} 46 | ] 47 | end 48 | 49 | # Copy the images referenced by docs, since ex_doc doesn't do this. 50 | defp copy_images(_) do 51 | File.cp_r "assets", "doc/assets" 52 | end 53 | end 54 | -------------------------------------------------------------------------------- /mix.lock: -------------------------------------------------------------------------------- 1 | %{"earmark": {:hex, :earmark, "1.2.0", "bf1ce17aea43ab62f6943b97bd6e3dc032ce45d4f787504e3adf738e54b42f3a", [:mix], []}, 2 | "elixir_ale": {:hex, :elixir_ale, "0.6.1", "475c8f57811bed621fb4d1118da4b0a40f3e3780609ddcf23a303879123fdf96", [:make, :mix], [{:elixir_make, "~> 0.4", [hex: :elixir_make, optional: false]}]}, 3 | "elixir_make": {:hex, :elixir_make, "0.4.0", "992f38fabe705bb45821a728f20914c554b276838433349d4f2341f7a687cddf", [:mix], []}, 4 | "ex_doc": {:hex, :ex_doc, "0.15.0", "e73333785eef3488cf9144a6e847d3d647e67d02bd6fdac500687854dd5c599f", [:mix], [{:earmark, "~> 1.1", [hex: :earmark, optional: false]}]}} 5 | -------------------------------------------------------------------------------- /test/ex_lcd/hd44780_test.exs: -------------------------------------------------------------------------------- 1 | defmodule ExLCD.HD44780Test do 2 | use ExUnit.Case 3 | use Bitwise 4 | alias ExLCD.HD44780 5 | 6 | setup do 7 | # Device config for testing 8 | config = %{ 9 | rs: 1, en: 2, d4: 4, d5: 5, d6: 6, d7: 7, 10 | rows: 2, cols: 20 11 | } 12 | 13 | # Mock the Hardware so we can inspect what happened 14 | with state = HD44780.start(config), 15 | {:ok, _} = MockHD44780.start_link(state) 16 | do 17 | %{state: state} 18 | end 19 | end 20 | 21 | describe "Command test:" do 22 | test "clear clears the display", %{state: state} do 23 | assert {:ok, _} = HD44780.command(state, {:clear, []}) 24 | assert 0x01 = stack_value() 25 | end 26 | 27 | test "home homes the cursor", %{state: state} do 28 | assert {:ok, _} = HD44780.command(state, {:home, []}) 29 | assert 0x02 = stack_value() 30 | end 31 | 32 | test "display turns on and off", %{state: state} do 33 | # 0b00001*CB 34 | assert {:ok, _} = HD44780.command(state, {:display, :on}) 35 | assert 0x0C = (stack_value() &&& 0x0C) 36 | assert {:ok, _} = HD44780.command(state, {:display, :off}) 37 | assert 0x08 = (stack_value() &&& 0x08) 38 | end 39 | 40 | test "cursor turns on and off", %{state: state} do 41 | # 0b00001D*B 42 | assert {:ok, _} = HD44780.command(state, {:cursor, :on}) 43 | assert 0x0A = (stack_value() &&& 0x0A) 44 | assert {:ok, _} = HD44780.command(state, {:cursor, :off}) 45 | assert 0x08 = (stack_value() &&& 0x08) 46 | end 47 | 48 | test "blink turns on and off", %{state: state} do 49 | # 0b00001DC* 50 | assert {:ok, _} = HD44780.command(state, {:blink, :on}) 51 | assert 0x09 = (stack_value() &&& 0x09) 52 | assert {:ok, _} = HD44780.command(state, {:blink, :off}) 53 | assert 0x08 = (stack_value() &&& 0x08) 54 | end 55 | 56 | test "autoscroll turns on and off", %{state: state} do 57 | # 0b00001DC* 58 | assert {:ok, _} = HD44780.command(state, {:autoscroll, :on}) 59 | assert 0x05 = (stack_value() &&& 0x05) 60 | assert {:ok, _} = HD44780.command(state, {:autoscroll, :off}) 61 | assert 0x04 = (stack_value() &&& 0x04) 62 | end 63 | 64 | test "rtl_text turns on", %{state: state} do 65 | # 0b00001DC* 66 | assert {:ok, _} = HD44780.command(state, {:rtl_text, :on}) 67 | assert 0x04 == stack_value() 68 | end 69 | 70 | test "ltr_text turns on", %{state: state} do 71 | # 0b00001DC* 72 | assert {:ok, _} = HD44780.command(state, {:ltr_text, :on}) 73 | assert 0x06 == stack_value() 74 | end 75 | 76 | test "shift screen left by one column", %{state: state} do 77 | # 0b0001CD0 78 | assert {:ok, _} = HD44780.command(state, {:scroll, -1}) 79 | assert 0x18 = (stack_value() &&& 0x18) 80 | end 81 | 82 | test "shift screen left by three columns", %{state: state} do 83 | # 0b0001CD0 84 | assert {:ok, _} = HD44780.command(state, {:scroll, -3}) 85 | %{stack: stack} = MockHD44780.status() 86 | assert [0x18, 0x18, 0x18] = stack 87 | end 88 | 89 | test "shift screen right by one column", %{state: state} do 90 | # 0b0001CD0 91 | assert {:ok, _} = HD44780.command(state, {:scroll, 1}) 92 | assert 0x1C = (stack_value() &&& 0x1C) 93 | end 94 | 95 | test "shift screen right by three columns", %{state: state} do 96 | # 0b0001CD0 97 | assert {:ok, _} = HD44780.command(state, {:scroll, 3}) 98 | %{stack: stack} = MockHD44780.status() 99 | assert [0x1C, 0x1C, 0x1C] = stack 100 | end 101 | 102 | test "move cursor left by one column", %{state: state} do 103 | # 0b0001CD0 104 | assert {:ok, _} = HD44780.command(state, {:left, 1}) 105 | assert 0x10 = (stack_value() &&& 0x10) 106 | end 107 | 108 | test "move cursor left by three columns", %{state: state} do 109 | # 0b0001CD0 110 | assert {:ok, _} = HD44780.command(state, {:left, 3}) 111 | %{stack: stack} = MockHD44780.status() 112 | assert [0x10, 0x10, 0x10] = stack 113 | end 114 | 115 | test "move cursor right by one column", %{state: state} do 116 | # 0b0001CD0 117 | assert {:ok, _} = HD44780.command(state, {:right, 1}) 118 | assert 0x14 = (stack_value() &&& 0x14) 119 | end 120 | 121 | test "move cursor right by three columns", %{state: state} do 122 | # 0b0001CD0 123 | assert {:ok, _} = HD44780.command(state, {:right, 3}) 124 | %{stack: stack} = MockHD44780.status() 125 | assert [0x14, 0x14, 0x14] = stack 126 | end 127 | 128 | test "move cursor to row 1, column 14 moves the cursor", %{state: state} do 129 | # 0b1aaaaaa - 0x40 + 0x0E , row 1 starts at 0x40, col 14 is offset 0xE from there 130 | assert {:ok, _} = HD44780.command(state, {:set_cursor, {1, 14}}) 131 | assert 0xCE = (stack_value() &&& 0xFF) 132 | end 133 | 134 | test "write hello world writes hello world", %{state: state} do 135 | assert {:ok, _} = HD44780.command(state, {:print, "hello world"}) 136 | %{stack: stack} = MockHD44780.status() 137 | written = stack 138 | |> Enum.map(fn(x) -> x &&& 0xFF end) 139 | assert 'hello world' = written 140 | end 141 | 142 | test "write a char list writes hello world", %{state: state} do 143 | assert {:ok, _} = HD44780.command(state, {:write, 'hello world'}) 144 | %{stack: stack} = MockHD44780.status() 145 | written = stack 146 | |> Enum.map(fn(x) -> x &&& 0xFF end) 147 | assert 'hello world' = written 148 | end 149 | 150 | test "write a list of chars write test", %{state: state} do 151 | assert {:ok, _} = HD44780.command(state, {:write, [?t, ?e, ?s, ?t]}) 152 | %{stack: stack} = MockHD44780.status() 153 | written = stack 154 | |> Enum.map(fn(x) -> x &&& 0xFF end) 155 | assert 'test' = written 156 | end 157 | 158 | test "creating a custom character creates a custom character", %{state: state} do 159 | char = [ 0b00001010, 160 | 0b00010101, 161 | 0b00001010, 162 | 0b00010101, 163 | 0b00001010, 164 | 0b00010101, 165 | 0b00001010, 166 | 0b00010101] 167 | assert {:ok, _} = HD44780.command(state, {:char, 3, char}) 168 | %{stack: stack} = MockHD44780.status() 169 | written = Enum.map(stack, fn(x) -> x &&& 0xFF end) 170 | assert [0x43] ++ char == written 171 | end 172 | end 173 | 174 | defp stack_value() do 175 | with %{stack: stack} = MockHD44780.status() 176 | do 177 | List.first(stack) 178 | end 179 | end 180 | end 181 | -------------------------------------------------------------------------------- /test/ex_lcd_test.exs: -------------------------------------------------------------------------------- 1 | defmodule ExLCDTest do 2 | use ExUnit.Case 3 | 4 | test "start_link starts a genserver and initializes its state" do 5 | assert {:ok, pid} = ExLCD.start_link({TestDriver, %{}}) 6 | assert Process.alive?(pid) 7 | end 8 | 9 | describe "cast operations" do 10 | setup do 11 | # A state for testing 12 | state = %ExLCD.LCDState{display: %{}, callback: &TestDriver.command/2} 13 | [state: state] 14 | end 15 | 16 | test "clear clears display", state do 17 | assert {:noreply, state} = ExLCD.handle_cast(:clear, state[:state]) 18 | assert {:clear, []} = state.display 19 | end 20 | 21 | test "home homes the cursor", state do 22 | assert {:noreply, state} = ExLCD.handle_cast(:home, state[:state]) 23 | assert {:home, []} = state.display 24 | end 25 | 26 | test "set_cursor positions the cursor", state do 27 | assert {:noreply, state} = ExLCD.handle_cast({:set_cursor, 1, 2}, state[:state]) 28 | assert {:set_cursor, {1, 2}} = state.display 29 | end 30 | 31 | test "write outputs some text", state do 32 | assert {:noreply, state} = ExLCD.handle_cast({:write, 'hello'}, state[:state]) 33 | assert {:write, 'hello'} = state.display 34 | end 35 | 36 | test "print outputs a string", state do 37 | assert {:noreply, state} = ExLCD.handle_cast({:write, "hello"}, state[:state]) 38 | assert {:write, "hello"} = state.display 39 | end 40 | 41 | test "scroll scrolls the display", state do 42 | assert {:noreply, state} = ExLCD.handle_cast({:scroll, 1}, state[:state]) 43 | assert {:scroll, 1} = state.display 44 | end 45 | 46 | test "move left moves the cursor left", state do 47 | assert {:noreply, state} = ExLCD.handle_cast({:left, 1}, state[:state]) 48 | assert {:left, 1} = state.display 49 | end 50 | 51 | test "move right moves the cursor right", state do 52 | assert {:noreply, state} = ExLCD.handle_cast({:right, 1}, state[:state]) 53 | assert {:right, 1} = state.display 54 | end 55 | 56 | test "enable enables a feature", state do 57 | assert {:noreply, state} = ExLCD.handle_cast({:enable, :foo}, state[:state]) 58 | assert {:foo, :on} = state.display 59 | end 60 | 61 | test "disable disables a feature", state do 62 | assert {:noreply, state} = ExLCD.handle_cast({:disable, :foo}, state[:state]) 63 | assert {:foo, :off} = state.display 64 | end 65 | 66 | test "char creates a custom glyph", state do 67 | char = <<0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF>> 68 | assert {:noreply, state} = ExLCD.handle_cast({:char, 6, char}, state[:state]) 69 | assert {:char, 6, ^char} = state.display 70 | end 71 | end 72 | end 73 | 74 | defmodule TestDriver do 75 | use ExLCD.Driver 76 | 77 | def start(config), do: {:ok, config} 78 | def stop(_), do: :ok 79 | def execute(), do: &command/2 80 | def command(_state, op), do: {:ok, op} 81 | end 82 | -------------------------------------------------------------------------------- /test/support/mock_hd44780.ex: -------------------------------------------------------------------------------- 1 | defmodule MockHD44780 do 2 | use GenServer 3 | use Bitwise 4 | 5 | @noisy false 6 | 7 | def start_link(display_state) do 8 | state = %{display_state: display_state, stack: [], register_state: 0x0000} 9 | GenServer.start_link(__MODULE__, state, name: __MODULE__) 10 | end 11 | 12 | def status() do 13 | GenServer.call(__MODULE__, :status) 14 | end 15 | 16 | def write(pin, value) do 17 | GenServer.cast(__MODULE__, {pin, value}) 18 | end 19 | 20 | def handle_call(:status, _, state) do 21 | {:reply, state, state} 22 | end 23 | 24 | def handle_cast({pin, value}, state) do 25 | {key, _} = state.display_state 26 | |> Map.take([:rs, :en, :d0, :d1, :d2, :d3, :d4, :d5, :d6, :d7]) 27 | |> Enum.find(fn({_k, v}) -> v == pin end) 28 | {:noreply, write_bit(state, key, value)} 29 | end 30 | 31 | def write_bit(state, pin, value) do 32 | xform = case value do 33 | 1 -> fn(x,y) -> x ||| y end 34 | 0 -> fn(x,y) -> x &&& (~~~y) end 35 | end 36 | noise "Pin(#{pin}) #{value} [#{hex(state.register_state)}]" 37 | set_bit(state, pin, value, xform) 38 | end 39 | 40 | @pin_map [d4: 0x10, d5: 0x20, d6: 0x40, d7: 0x80, 41 | d0: 0x01, d1: 0x02, d2: 0x04, d3: 0x08] 42 | 43 | # Toggling EN high latches the register. Push it to the stack and reset 44 | defp set_bit(state, :en, 0, _), do: state 45 | defp set_bit(state = %{register_state: register_state}, :en, 1, _) do 46 | noise "Register " <> hex(register_state, 4) 47 | # is the done flag set? 48 | {stack, register_state} = case register_state &&& 0x0200 do 49 | 0x200 -> 50 | # push register to the stack and reset register 51 | {state.stack ++ [(register_state &&& 0x1FF)], 0} 52 | _ -> 53 | # Set finish flag to complete register write on next EN high 54 | {state.stack, (register_state &&& 0x01FF) ||| 0x0200} 55 | end 56 | 57 | %{state | stack: stack, register_state: register_state} 58 | end 59 | 60 | defp set_bit(state, :rs, _, xform) do 61 | new_register_state = xform.(state.register_state, 0x0100) 62 | %{state | register_state: new_register_state} 63 | end 64 | 65 | # If the 10th bit is set then d7 was written to so we either need an EN high 66 | # to latch the data or the next write to d4-d7 will be the low order bits 67 | # in a 4 bit interface. 68 | 69 | defp set_bit(state, :d7, _, xform) do 70 | shifted_value = case state.register_state >>> 9 do 71 | 0 -> @pin_map[:d7] 72 | 1 -> @pin_map[:d7] >>> 4 73 | end 74 | new_register_state = xform.(state.register_state, shifted_value) 75 | %{state | register_state: new_register_state} 76 | end 77 | 78 | defp set_bit(state, pin, _, xform) when pin in [:d4, :d5, :d6] do 79 | shifted_value = case state.register_state >>> 9 do 80 | 0 -> @pin_map[pin] 81 | 1 -> @pin_map[pin] >>> 4 82 | end 83 | new_register_state = xform.(state.register_state, shifted_value) 84 | %{state | register_state: new_register_state} 85 | end 86 | 87 | # Writing to d0-d3 forces finish on next EN high (8-bit mode) 88 | 89 | defp set_bit(state, pin, _, xform) do 90 | new_register_state = xform.(state.register_state, @pin_map[pin]) ||| 0x0200 91 | %{state | register_state: new_register_state} 92 | end 93 | 94 | defp noise(str) do 95 | if @noisy do 96 | IO.puts str 97 | end 98 | end 99 | 100 | defp hex(value, width \\ 2) do 101 | padded = Integer.to_string(value, 16) 102 | |> String.pad_leading(width, "0") 103 | "0x" <> padded 104 | end 105 | end 106 | -------------------------------------------------------------------------------- /test/test_helper.exs: -------------------------------------------------------------------------------- 1 | ExUnit.start() 2 | --------------------------------------------------------------------------------