mpl115_spi.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Freescale MPL115A1 pressure/temperature sensor
  4. *
  5. * Copyright (c) 2016 Akinobu Mita <[email protected]>
  6. *
  7. * Datasheet: http://www.nxp.com/files/sensors/doc/data_sheet/MPL115A1.pdf
  8. */
  9. #include <linux/module.h>
  10. #include <linux/spi/spi.h>
  11. #include "mpl115.h"
  12. #define MPL115_SPI_WRITE(address) ((address) << 1)
  13. #define MPL115_SPI_READ(address) (0x80 | (address) << 1)
  14. struct mpl115_spi_buf {
  15. u8 tx[4];
  16. u8 rx[4];
  17. };
  18. static int mpl115_spi_init(struct device *dev)
  19. {
  20. struct spi_device *spi = to_spi_device(dev);
  21. struct mpl115_spi_buf *buf;
  22. buf = devm_kzalloc(dev, sizeof(*buf), GFP_KERNEL);
  23. if (!buf)
  24. return -ENOMEM;
  25. spi_set_drvdata(spi, buf);
  26. return 0;
  27. }
  28. static int mpl115_spi_read(struct device *dev, u8 address)
  29. {
  30. struct spi_device *spi = to_spi_device(dev);
  31. struct mpl115_spi_buf *buf = spi_get_drvdata(spi);
  32. struct spi_transfer xfer = {
  33. .tx_buf = buf->tx,
  34. .rx_buf = buf->rx,
  35. .len = 4,
  36. };
  37. int ret;
  38. buf->tx[0] = MPL115_SPI_READ(address);
  39. buf->tx[2] = MPL115_SPI_READ(address + 1);
  40. ret = spi_sync_transfer(spi, &xfer, 1);
  41. if (ret)
  42. return ret;
  43. return (buf->rx[1] << 8) | buf->rx[3];
  44. }
  45. static int mpl115_spi_write(struct device *dev, u8 address, u8 value)
  46. {
  47. struct spi_device *spi = to_spi_device(dev);
  48. struct mpl115_spi_buf *buf = spi_get_drvdata(spi);
  49. struct spi_transfer xfer = {
  50. .tx_buf = buf->tx,
  51. .len = 2,
  52. };
  53. buf->tx[0] = MPL115_SPI_WRITE(address);
  54. buf->tx[1] = value;
  55. return spi_sync_transfer(spi, &xfer, 1);
  56. }
  57. static const struct mpl115_ops mpl115_spi_ops = {
  58. .init = mpl115_spi_init,
  59. .read = mpl115_spi_read,
  60. .write = mpl115_spi_write,
  61. };
  62. static int mpl115_spi_probe(struct spi_device *spi)
  63. {
  64. const struct spi_device_id *id = spi_get_device_id(spi);
  65. return mpl115_probe(&spi->dev, id->name, &mpl115_spi_ops);
  66. }
  67. static const struct spi_device_id mpl115_spi_ids[] = {
  68. { "mpl115", 0 },
  69. {}
  70. };
  71. MODULE_DEVICE_TABLE(spi, mpl115_spi_ids);
  72. static struct spi_driver mpl115_spi_driver = {
  73. .driver = {
  74. .name = "mpl115",
  75. },
  76. .probe = mpl115_spi_probe,
  77. .id_table = mpl115_spi_ids,
  78. };
  79. module_spi_driver(mpl115_spi_driver);
  80. MODULE_AUTHOR("Akinobu Mita <[email protected]>");
  81. MODULE_DESCRIPTION("Freescale MPL115A1 pressure/temperature driver");
  82. MODULE_LICENSE("GPL");
  83. MODULE_IMPORT_NS(IIO_MPL115);