main.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. #include <avr/io.h>
  2. #include <util/delay.h>
  3. #include <stdlib.h>
  4. //SREG defines
  5. #define S_MOSI PB3
  6. #define S_MISO PB4
  7. #define S_SCK PB5
  8. #define S_LATCH PB2
  9. //DEBUG defines
  10. #define D_LED0 PC5
  11. //SRAM defines
  12. #define R_WR PB6
  13. #define R_RD PB7
  14. #define R_DATA PORTD
  15. #define R_DIR DDRD
  16. void SPI_MasterInit(void)
  17. {
  18. /* Set MOSI and SCK output, all others input */
  19. DDRB |= ((1<<S_MOSI) | (1<<S_SCK) | (1<<S_LATCH));
  20. DDRB &= ~(1<<S_MISO);
  21. PORTB |= (1<<S_MISO);
  22. /* Enable SPI, Master*/
  23. SPCR = ((1<<SPE) | (1<<MSTR));
  24. }
  25. void SPI_MasterTransmit(unsigned char cData)
  26. {
  27. /* Start transmission */
  28. SPDR = cData;
  29. /* Wait for transmission complete */
  30. while(!(SPSR & (1<<SPIF)));
  31. }
  32. uint8_t SRAM_Read(uint32_t addr)
  33. {
  34. uint8_t byte;
  35. DDRD=0x00;
  36. PORTD=0xff;
  37. PORTB |= (1<<R_RD);
  38. PORTB |= (1<<R_WR);
  39. SPI_MasterTransmit((uint8_t)(addr>>16));
  40. SPI_MasterTransmit((uint8_t)(addr>>8));
  41. SPI_MasterTransmit((uint8_t)(addr>>0));
  42. PORTB |= (1<<S_LATCH);
  43. PORTB &= ~(1<<S_LATCH);
  44. PORTB &= ~(1<<R_RD);
  45. asm volatile ("nop");
  46. asm volatile ("nop");
  47. asm volatile ("nop");
  48. byte = PIND;
  49. PORTB |= (1<<R_RD);
  50. DDRD=0x00;
  51. PORTD=0x00;
  52. return byte;
  53. }
  54. void SRAM_Write(uint32_t addr, uint8_t data)
  55. {
  56. DDRD=0xff;
  57. PORTB |= (1<<R_RD);
  58. PORTB |= (1<<R_WR);
  59. SPI_MasterTransmit((uint8_t)(addr>>16));
  60. SPI_MasterTransmit((uint8_t)(addr>>8));
  61. SPI_MasterTransmit((uint8_t)(addr>>0));
  62. PORTB |= (1<<S_LATCH);
  63. PORTB &= ~(1<<S_LATCH);
  64. PORTB &= ~(1<<R_WR);
  65. PORTD=data;
  66. PORTB |= (1<<R_WR);
  67. DDRD=0x00;
  68. PORTD=0x00;
  69. }
  70. int main(void)
  71. {
  72. DDRB|= (1 << PB1);
  73. PORTB|= (1 << PB1);
  74. while(1);
  75. return(0);
  76. }