Paso 3: Escribir un programa
Tenemos que incluir la biblioteca de la serie.
#include "mbed.h" #include <Serial.h><br>
#define BAUD 9600 // speed of transmission #define BUFFER_SIZE 20 // buffer for password
#define ENTER 0x0d // Enter button in HEX
Serial uart1(PTE0,PTE1,"uart1"); DigitalOut redLed(LED2); // set red led pin as output DigitalOut greenLed(LED1); // set green led pin as output
void usart_Init(size_t baud); // uart init char *get_string(void);
char *command = "password";
int main() { char *c; usart_Init(BAUD); // initialize usart redLed.write(1); // turn off LEDs greenLed.write(1); uart1.printf("\n\rProgram is starting now...\n\r"); // print text in terminal uart1.printf("Baud rate - %d\n\r",BAUD); while (1) { c = get_string(); // c = string from terminal if(strcmp(c,command) == 0) // if string is the same as "password" { greenLed.write(0); // turn on LED uart1.printf("\n\rCorrect password !"); // print message } else { redLed.write(0); // turn red LED on uart1.printf("\n\rWrong password"); } greenLed.write(1); // turn LEDs off redLed.write(1); } }
void usart_Init(size_t baud) { uart1.baud(baud); // Set baud rate uart1.format(); // Defaut: 8 bit data, no parity, 1 stop bit }
char *get_string(void) { char buffer[BUFFER_SIZE]; char *strBuf = buffer; // put pointer on buffer int i = 0, cnt=0; char c; while((c = uart1.getc()) != ENTER) // while char is not ENTER { buffer[i] = c; // put char to the buffer i++, cnt++; } if(cnt <= BUFFER_SIZE) { for(i = cnt; i < BUFFER_SIZE; i++) // if data is shortest than buffer size { // then put NULLs after string buffer[i] = '\0'; // ex. exampleString'\0''\0''\0'../ } } else { uart1.printf("\n\rWrong string size !"); } return strBuf; }