at24c32_stc8h3k.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright 2021 IOsetting <iosetting(at)outlook.com>
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /***
  15. * Demo: AT24C32
  16. * Board: STC8H3K32
  17. *
  18. * P32 -> SCL
  19. * P33 -> SDA
  20. * GND -> GND, A0, A1, A2
  21. * 3.3V -> VCC
  22. */
  23. #include "fw_hal.h"
  24. // AT24C device address, change according to the voltage level of A0/A1/A2
  25. #define AT24C_ADDR 0xA0
  26. // Test data
  27. __CODE int8_t dat[20] = {0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB};
  28. void I2C_Init(void)
  29. {
  30. // Master mode
  31. I2C_SetWorkMode(I2C_WorkMode_Master);
  32. /**
  33. * I2C clock = FOSC / 2 / (__prescaler__ * 2 + 4)
  34. */
  35. I2C_SetClockPrescaler(0x3F);
  36. // Switch alternative port
  37. I2C_SetPort(I2C_AlterPort_P32_P33);
  38. // Start I2C
  39. I2C_SetEnabled(HAL_State_ON);
  40. }
  41. void GPIO_Init(void)
  42. {
  43. // SDA
  44. GPIO_P3_SetMode(GPIO_Pin_3, GPIO_Mode_InOut_QBD);
  45. // SCL
  46. GPIO_P3_SetMode(GPIO_Pin_2, GPIO_Mode_Output_PP);
  47. }
  48. int main(void)
  49. {
  50. uint8_t offset, i, buf[20];
  51. SYS_SetClock();
  52. // UART1 configuration: baud 115200 with Timer2, 1T mode, no interrupt
  53. UART1_Config8bitUart(UART1_BaudSource_Timer2, HAL_State_ON, 115200);
  54. GPIO_Init();
  55. I2C_Init();
  56. I2C_Write16BitAddr(AT24C_ADDR, 0x0000, dat, 12);
  57. while(1)
  58. {
  59. for (offset = 0; offset < 4; offset++)
  60. {
  61. I2C_Read16BitAddr(AT24C_ADDR, 0x0000|offset, buf, 6);
  62. for (i = 0; i < 6; i++)
  63. {
  64. UART1_TxHex(buf[i]);
  65. UART1_TxChar(':');
  66. }
  67. UART1_TxString(" ");
  68. SYS_Delay(10);
  69. }
  70. UART1_TxString("\r\n");
  71. SYS_Delay(1000);
  72. }
  73. }