OpenCores
URL https://opencores.org/ocsvn/neorv32/neorv32/trunk

Subversion Repositories neorv32

[/] [neorv32/] [trunk/] [sw/] [example/] [demo_twi/] [main.c] - Blame information for rev 44

Go to most recent revision | Details | Compare with Previous | View Log

Line No. Rev Author Line
1 2 zero_gravi
// #################################################################################################
2
// # << NEORV32 - TWI Bus Explorer Demo Program >>                                                 #
3
// # ********************************************************************************************* #
4
// # BSD 3-Clause License                                                                          #
5
// #                                                                                               #
6 44 zero_gravi
// # Copyright (c) 2021, Stephan Nolting. All rights reserved.                                     #
7 2 zero_gravi
// #                                                                                               #
8
// # Redistribution and use in source and binary forms, with or without modification, are          #
9
// # permitted provided that the following conditions are met:                                     #
10
// #                                                                                               #
11
// # 1. Redistributions of source code must retain the above copyright notice, this list of        #
12
// #    conditions and the following disclaimer.                                                   #
13
// #                                                                                               #
14
// # 2. Redistributions in binary form must reproduce the above copyright notice, this list of     #
15
// #    conditions and the following disclaimer in the documentation and/or other materials        #
16
// #    provided with the distribution.                                                            #
17
// #                                                                                               #
18
// # 3. Neither the name of the copyright holder nor the names of its contributors may be used to  #
19
// #    endorse or promote products derived from this software without specific prior written      #
20
// #    permission.                                                                                #
21
// #                                                                                               #
22
// # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS   #
23
// # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF               #
24
// # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE    #
25
// # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,     #
26
// # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE #
27
// # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED    #
28
// # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING     #
29
// # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED  #
30
// # OF THE POSSIBILITY OF SUCH DAMAGE.                                                            #
31
// # ********************************************************************************************* #
32
// # The NEORV32 Processor - https://github.com/stnolting/neorv32              (c) Stephan Nolting #
33
// #################################################################################################
34
 
35
 
36
/**********************************************************************//**
37
 * @file demo_twi/main.c
38
 * @author Stephan Nolting
39
 * @brief TWI bus explorer.
40
 **************************************************************************/
41
 
42
#include <neorv32.h>
43 14 zero_gravi
#include <string.h>
44 2 zero_gravi
 
45
 
46
/**********************************************************************//**
47
 * @name User configuration
48
 **************************************************************************/
49
/**@{*/
50
/** UART BAUD rate */
51
#define BAUD_RATE 19200
52
/**@}*/
53
 
54
 
55
// Prototypes
56
void scan_twi(void);
57
void set_speed(void);
58
void send_twi(void);
59
uint32_t hexstr_to_uint(char *buffer, uint8_t length);
60
 
61
 
62
/**********************************************************************//**
63 35 zero_gravi
 * This program provides an interactive console to communicate with TWI devices.
64 2 zero_gravi
 *
65 35 zero_gravi
 * @note This program requires the UART and the PWM to be synthesized.
66 2 zero_gravi
 *
67
 * @return Irrelevant.
68
 **************************************************************************/
69
int main() {
70
 
71
  char buffer[8];
72
  int length = 0;
73
  int bus_claimed = 0;
74
 
75
  // check if UART unit is implemented at all
76
  if (neorv32_uart_available() == 0) {
77
    return 0;
78
  }
79
 
80
 
81
  // capture all exceptions and give debug info via UART
82
  // this is not required, but keeps us safe
83 14 zero_gravi
  neorv32_rte_setup();
84 2 zero_gravi
 
85
 
86 42 zero_gravi
  // init UART at default baud rate, no parity bits, no rx interrupt, no tx interrupt
87
  neorv32_uart_setup(BAUD_RATE, 0b00, 0, 0);
88 2 zero_gravi
 
89 44 zero_gravi
  // check available hardware extensions and compare with compiler flags
90
  neorv32_rte_check_isa(0); // silent = 0 -> show message if isa mismatch
91
 
92 2 zero_gravi
  // intro
93
  neorv32_uart_printf("\n--- TWI Bus Explorer ---\n\n");
94
 
95
 
96
  // check if TWI unit is implemented at all
97
  if (neorv32_twi_available() == 0) {
98
    neorv32_uart_printf("No TWI unit implemented.");
99
    return 0;
100
  }
101
 
102
 
103
  // info
104
  neorv32_uart_printf("This program allows to create TWI transfers by hand.\n"
105
                      "Type 'help' to see the help menu.\n\n");
106
 
107 35 zero_gravi
  // configure TWI, second slowest clock, no IRQ, no clock-stretching
108
  neorv32_twi_setup(CLK_PRSC_2048, 0, 0);
109 2 zero_gravi
 
110
  // no active bus session yet
111
  bus_claimed = 0;
112
 
113
  // Main menu
114
  for (;;) {
115
    neorv32_uart_printf("TWI_EXPLORER:> ");
116
    length = neorv32_uart_scan(buffer, 8, 1);
117
    neorv32_uart_printf("\n");
118
 
119
    if (!length) // nothing to be done
120
     continue;
121
 
122
    // decode input and execute command
123
    if (!strcmp(buffer, "help")) {
124
      neorv32_uart_printf("Available commands:\n"
125
                          " help  - show this text\n"
126
                          " scan  - scan bus for devices\n"
127
                          " start - generate START condition\n"
128
                          " stop  - generate STOP condition\n"
129
                          " send  - write & read single byte to/from bus\n"
130
                          " speed - select bus clock\n"
131
                          "Start a new transmission by generating a START condition. Next, transfer the 7-bit device address\n"
132
                          "and the R/W flag. After that, transfer your data to be written or send a 0xFF if you want to read\n"
133
                          "data from the bus. Finish the transmission by generating a STOP condition.\n\n");
134
    }
135
    else if (!strcmp(buffer, "start")) {
136
      neorv32_twi_generate_start(); // generate START condition
137
      bus_claimed = 1;
138
    }
139
    else if (!strcmp(buffer, "stop")) {
140
      if (bus_claimed == 0) {
141
        neorv32_uart_printf("No active I2C transmission.\n");
142
        continue;
143
      }
144
      neorv32_twi_generate_stop(); // generate STOP condition
145
      bus_claimed = 0;
146
    }
147
    else if (!strcmp(buffer, "scan")) {
148
      scan_twi();
149
    }
150
    else if (!strcmp(buffer, "speed")) {
151
      set_speed();
152
    }
153
    else if (!strcmp(buffer, "send")) {
154
      if (bus_claimed == 0) {
155
        neorv32_uart_printf("No active I2C transmission. Generate a START condition first.\n");
156
        continue;
157
      }
158
      else {
159
        send_twi();
160
      }
161
    }
162
    else {
163
      neorv32_uart_printf("Invalid command. Type 'help' to see all commands.\n");
164
    }
165
  }
166
 
167
  return 0;
168
}
169
 
170
 
171
/**********************************************************************//**
172
 * TWI clock speed menu
173
 **************************************************************************/
174
void set_speed(void) {
175
 
176
  char terminal_buffer[2];
177
 
178
  neorv32_uart_printf("Select new clock prescaler (0..7): ");
179
  neorv32_uart_scan(terminal_buffer, 2, 1); // 1 hex char plus '\0'
180
  uint8_t prsc = (uint8_t)hexstr_to_uint(terminal_buffer, strlen(terminal_buffer));
181
  if ((prsc >= 0) && (prsc < 8)) { // valid?
182
    TWI_CT = 0; // reset
183
    TWI_CT = (1 << TWI_CT_EN) | (prsc << TWI_CT_PRSC0);
184
    neorv32_uart_printf("\nDone.\n");
185
  }
186
  else {
187
    neorv32_uart_printf("\nInvalid selection!\n");
188
    return;
189
  }
190
 
191
  // print new clock frequency
192 12 zero_gravi
  uint32_t clock = SYSINFO_CLK;
193 2 zero_gravi
  switch (prsc) {
194
    case 0: clock = clock / 2; break;
195
    case 1: clock = clock / 4; break;
196
    case 2: clock = clock / 8; break;
197
    case 3: clock = clock / 64; break;
198
    case 4: clock = clock / 128; break;
199
    case 5: clock = clock / 1024; break;
200
    case 6: clock = clock / 2048; break;
201
    case 7: clock = clock / 4096; break;
202
    default: clock = 0; break;
203
  }
204
  neorv32_uart_printf("New I2C clock: %u Hz\n", clock);
205
}
206
 
207
 
208
/**********************************************************************//**
209
 * Scan 7-bit TWI address space and print results
210
 **************************************************************************/
211
void scan_twi(void) {
212
 
213
  neorv32_uart_printf("Scanning TWI bus...\n");
214
  uint8_t i, num_devices = 0;
215
  for (i=0; i<128; i++) {
216
    uint8_t twi_ack = neorv32_twi_start_trans((uint8_t)(2*i+1));
217
    neorv32_twi_generate_stop();
218
 
219
    if (twi_ack == 0) {
220
      neorv32_uart_printf("+ Found device at write-address 0x%x\n", (uint32_t)(2*i));
221
      num_devices++;
222
    }
223
  }
224
 
225
  if (!num_devices) {
226
    neorv32_uart_printf("No devices found.\n");
227
  }
228
}
229
 
230
 
231
/**********************************************************************//**
232
 * Read/write menu to transfer 1 byte from/to bus
233
 **************************************************************************/
234
void send_twi(void) {
235
 
236
  char terminal_buffer[4];
237
 
238
  // enter data
239
  neorv32_uart_printf("Enter TX data (2 hex chars): ");
240
  neorv32_uart_scan(terminal_buffer, 3, 1); // 2 hex chars for address plus '\0'
241
  uint8_t tmp = (uint8_t)hexstr_to_uint(terminal_buffer, strlen(terminal_buffer));
242
  uint8_t res = neorv32_twi_trans(tmp);
243
  neorv32_uart_printf("\nRX data:  0x%x\n", (uint32_t)neorv32_twi_get_data());
244
  neorv32_uart_printf("Response: ");
245
  if (res == 0)
246
    neorv32_uart_printf("ACK\n");
247
  else
248
    neorv32_uart_printf("NACK\n");
249
 
250
}
251
 
252
 
253
/**********************************************************************//**
254
 * Helper function to convert N hex chars string into uint32_T
255
 *
256
 * @param[in,out] buffer Pointer to array of chars to convert into number.
257
 * @param[in,out] length Length of the conversion string.
258
 * @return Converted number.
259
 **************************************************************************/
260
uint32_t hexstr_to_uint(char *buffer, uint8_t length) {
261
 
262
  uint32_t res = 0, d = 0;
263
  char c = 0;
264
 
265
  while (length--) {
266
    c = *buffer++;
267
 
268
    if ((c >= '0') && (c <= '9'))
269
      d = (uint32_t)(c - '0');
270
    else if ((c >= 'a') && (c <= 'f'))
271
      d = (uint32_t)((c - 'a') + 10);
272
    else if ((c >= 'A') && (c <= 'F'))
273
      d = (uint32_t)((c - 'A') + 10);
274
    else
275
      d = 0;
276
 
277
    res = res + (d << (length*4));
278
  }
279
 
280
  return res;
281
}

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.