Project to use Serial with registers

Dependencies:   mbed

main.cpp

Committer:
SimonNOWAK
Date:
2017-04-05
Revision:
4:d9c6de483827
Parent:
3:fba5fc24faff

File content as of revision 4:d9c6de483827:

#include "mbed.h"

DigitalOut myled(LED1);
Serial pc(USBTX, USBRX);

void usartSetup (void) {
    RCC->IOPENR |= RCC_IOPENR_IOPBEN;
    RCC->APB2ENR |= RCC_APB2ENR_USART1EN;            // enable clock for USART1
    USART1->BRR  = 320000 / 96;              // set baudrate
    GPIOB->MODER &= ~GPIO_MODER_MODE6_0;
    GPIOB->MODER |= GPIO_MODER_MODE6_1;
    
    GPIOB->MODER &= ~GPIO_MODER_MODE7_0;
    GPIOB->MODER |= GPIO_MODER_MODE7_1;
    
/*    GPIOB->AFR[0] |= 0x40;*/
    GPIOB->OTYPER &= ~GPIO_OTYPER_OT_6;
    GPIOB->OTYPER |= GPIO_OTYPER_OT_7;
    USART1->CR1 |= (USART_CR1_RXNEIE | USART_CR1_RE | USART_CR1_TE | USART_CR1_UE);  // RX, TX enable
}

void SendChar(char Array[], int size){
    
    for(int send = 0; send < size; send++){
        //On attend que la transmission soit terminée
        while((USART1->ISR & USART_ISR_TC) != USART_ISR_TC);
        
        //Si on a tout envoyé
        if(send == size)
        {
            send=0;
            USART1->ICR = USART_ICR_TCCF; /* Clear transfer complete flag */
        }
        else
        {
            //Si le registre de données est vide
            while (!(USART1->ISR & (USART1->ISR | USART_ISR_TXE)));
            USART1->TDR = Array[send];
        }
    }
}

void ReceiveChar(int TimeOut){
    char buffer[300] = {0};
    int counter = 0;
    for(int i = 0; i < TimeOut; i++){
        if((USART1->ISR & USART_ISR_RXNE) == USART_ISR_RXNE){
            //buffer[counter] = (uint8_t)(USART1->RDR); // Receive data, clear flag
            pc.printf("%02X", USART1->RDR);
            counter++;
            myled = 1; // LED is ON
        }
        if(counter >= sizeof(buffer)){
            break;
        }
    }
    int sizeBuffer = sizeof(buffer);
    SendChar(buffer, sizeBuffer);
}

int main() {
    usartSetup();
    char stringtosend[] = {"Salut ca va ? Oui et toi ? Oh yes ca fonctionne bien ahahahahahahahahahahahah\r\n"};
    int sizeArray = sizeof(stringtosend);
    SendChar(stringtosend, sizeArray);
    ReceiveChar(500);
}