|
| 1 | +/* File: adc_demo.c |
| 2 | + * --------------- |
| 3 | + * SPI + MCP3008 adc test |
| 4 | + * |
| 5 | + * Breadboard configured for analog inputs: |
| 6 | + * 2-axis joystick channels 0/1 |
| 7 | + * Photoresistor channel 6 |
| 8 | + * Force sensor channel 7 |
| 9 | + */ |
| 10 | + |
| 11 | +#include "assert.h" |
| 12 | +#include "uart.h" |
| 13 | +#include "mcp3008.h" |
| 14 | +#include "printf.h" |
| 15 | +#include "strings.h" |
| 16 | +#include "timer.h" |
| 17 | + |
| 18 | +static const int MAX_VALUE = 1024; |
| 19 | + |
| 20 | +#define STRINGIFY_IMPL(x) #x |
| 21 | +#define AS_STRING(x) STRINGIFY_IMPL(x) |
| 22 | +#define ANSI_ESC(n) "\e[" AS_STRING(n) "m" |
| 23 | + |
| 24 | +#define RED ANSI_ESC(41) |
| 25 | +#define GREEN ANSI_ESC(42) |
| 26 | +#define YELLOW ANSI_ESC(43) |
| 27 | +#define BLUE ANSI_ESC(44) |
| 28 | +#define MAGENTA ANSI_ESC(45) |
| 29 | +#define CYAN ANSI_ESC(46) |
| 30 | +#define WHITE ANSI_ESC(47) |
| 31 | +#define NORMAL ANSI_ESC(0) |
| 32 | + |
| 33 | + |
| 34 | +static void print_analog_scale(int val, const char *label, const char *color) { |
| 35 | + assert(val <= MAX_VALUE); |
| 36 | + int quanta = 30; |
| 37 | + int on_quantized = val/quanta; |
| 38 | + int off_quantized = MAX_VALUE/quanta - on_quantized; |
| 39 | + char buf_on[on_quantized+1]; |
| 40 | + char buf_off[off_quantized+1]; |
| 41 | + memset(buf_off, ' ', sizeof(buf_off)); |
| 42 | + memset(buf_on, '-', sizeof(buf_on)); |
| 43 | + buf_on[sizeof(buf_on)-1] = '\0'; |
| 44 | + buf_off[sizeof(buf_off)-1] = '\0'; |
| 45 | + printf("%12s [%s%s%s%s]", label, color, buf_on, NORMAL, buf_off); |
| 46 | +} |
| 47 | + |
| 48 | +static void print_dashboard(int vert, int horiz, int light, int force){ |
| 49 | + printf("\f\n mcp3008 Readings \n\n"); |
| 50 | + print_analog_scale(vert, "Joy vert", CYAN); |
| 51 | + print_analog_scale(horiz, "Joy horiz", GREEN); |
| 52 | + printf("\n\n"); |
| 53 | + print_analog_scale(light, "Light:", WHITE); |
| 54 | + printf("\n\n"); |
| 55 | + print_analog_scale(force, "Force:", RED); |
| 56 | +} |
| 57 | + |
| 58 | +void main(void) { |
| 59 | + gpio_init(); |
| 60 | + uart_init(); |
| 61 | + mcp3008_init(); |
| 62 | + printf("Starting program %s\n\n", __FILE__); |
| 63 | + |
| 64 | + while (1) { |
| 65 | + int vert = mcp3008_read(0); |
| 66 | + int horiz = mcp3008_read(1); |
| 67 | + int light = mcp3008_read(6); |
| 68 | + int force = mcp3008_read(7); |
| 69 | + print_dashboard(vert, horiz, light, force); |
| 70 | + timer_delay_ms(100); |
| 71 | + } |
| 72 | +} |
0 commit comments