STM32F103RB Nucleo transmit and receive usart - c

I have some problems with transmiting and receiving using usart. First informations that I want transmit are writen to circle buffer. Then indormations are send but some informations are lost.
Variables
enum {
BUF_SIZE = 100
};
char BUF_T[BUF_SIZE], BUF_R[BUF_SIZE];
uint8_t R_EMPTY = 0, R_BUSY = 0, T_EMPTY = 0, T_BUSY = 0;
Transmiting
void Send(void) {
uint8_t index = T_EMPTY;
for (int i = 0; i < 10; i++) {
BUF_T[index] = i+'0';
index++;
if (index >= BUF_SIZE) {
index = 0;
}
}
__disable_irq();
if (T_BUSY == T_EMPTY
&& __HAL_UART_GET_FLAG(&huart2,UART_FLAG_TXE) == SET) {
T_EMPTY = index;
T_BUSY++;
uint8_t tmp = BUF_T[T_BUSY];
if (T_BUSY >= BUF_SIZE) {
T_BUSY = 0;
}
HAL_UART_Transmit_IT(&huart2, (uint8_t*) &tmp, 1);
} else {
T_EMPTY = index;
}
__enable_irq();
}
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) {
//if (huart->Instance == USART2) {
if (T_BUSY != T_EMPTY) {
__disable_irq();
T_BUSY++;
uint8_t tmp = BUF_T[T_BUSY];
if (T_BUSY >= BUF_SIZE) {
T_BUSY = 0;
}
HAL_UART_Transmit_IT(&huart2, (uint8_t*) &tmp, 1);
__enable_irq();
}else {
Send();
}
//}
}
Screen from hterm
On picture can be seen that from time to time one char is lost. I don't understant why?
Regarding receiving can somebody tell mi if it OK?
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
//if (huart->Instance == USART2) {
uint8_t tmp = BUF_R[R_EMPTY];
R_EMPTY++;
if (R_EMPTY >= BUF_SIZE) {
R_EMPTY = 0;
}
HAL_UART_Receive_IT(&huart2, (uint8_t*) &tmp, 1);
//}
}

Related

How to setup stop condition on VEML7700 through I2C library? I am not getting the ACK from reading

int I2C_Master_ReadReg(unsigned char dev_addr, unsigned char reg_addr, unsigned char count, unsigned char *pData, void (* Sub)(void)) {
uint8_t cnt;
start();
sda(dev_addr);
if (!(dev_addr == 0x10)) {
cnt = 0;
}
if (count > 0x05) {
cnt = 0;
}
if (clk() == 1) {
I2C_Ack_Error(1);
return -1;
}
sda(reg_addr + 0);
if (clk() == 1) {
I2C_Ack_Error(2);
return -2;
}
start();
sda(dev_addr + 1);
if (clk() == 1) {
I2C_Ack_Error(3);
return -3;
}
for (cnt = 0; cnt < count; ++cnt) {
*(pData + cnt) = read();
//printf("D: %x\n\r", read());
if (clk() == 0) {
I2C_Ack_Error(4);
return -4;
}
stop();
}
return 0;
}

My while loop is not breaking after my interrupt updates in C

I am implementing simon says as a small weekly project for school. Using arduino Uno, I'm making 10 levels each level has an extra pattern inside. example: level 1: [1], level 2: [1,2], etc... I have three buttons on my shield. the interrupts work and everything is gucci. My problem here is in this snippet
bool readInput(uint8_t pattern[], uint8_t length)
{
sei();
uint8_t current = 0;
while (current < length)
{
btnPushed = false;
while (!btnPushed)
{
#ifdef DEBUG
_delay_ms(1);
#endif
}
printf("here");
cli();
_delay_ms(200);
if (currentPushed == pattern[current])
{
printf("correct, you pushed %d\n", currentPushed);
}
else
{
printf("incorrect, lets try again\n");
return false;
}
}
btnPushed = false;
return true;
}
so basically I set my buttonPushed to false, and start listening for interrupts, once its true after clicking, I expect to exit the loop and check the input, however my interrupt is correct and I get visual feedback with a light that lights up once i push a button.
this is my ISR
ISR(PCINT1_vect)
{
uint8_t buttonCurr = currentButton();
if (buttonCurr != -1)
{
if (!btn1Pushed && buttonCurr == 0)
{
btn1Pushed = true;
}
currentPushed = buttonCurr;
blinkLed(currentPushed, 1);
btnPushed = true;
}
}
my current button returns 0-2 for buttons that are clicked, and -1 if nothing was clicked.
this is the rest of my code, which is working pretty much
int currentPushed = -1;
bool won;
bool btnPushed = false;
bool btn1Pushed = false;
ISR(PCINT1_vect)
{
uint8_t buttonCurr = currentButton();
if (buttonCurr != -1)
{
if (!btn1Pushed && buttonCurr == 0)
{
btn1Pushed = true;
}
currentPushed = buttonCurr;
blinkLed(currentPushed, 1);
btnPushed = true;
}
}
int main(void)
{
enableAllButtons();
enableAllLeds();
lightDownAllLeds();
prepareButtonsForInterrupt();
initUSART();
init();
play();
if (won)
{
printf("Simon says you win");
}
else
{
printf("simon says do better");
}
return 0;
}
void init(void)
{
printf("LETS PLAY SIMON SAYS\nPress button 1 to start!\n");
int seed = 0;
while (!btn1Pushed)
{
blinkLed(3, 4);
seed++;
}
srand(seed);
printf("Get ready!\n");
btnPushed = false;
cli();
}
void createRandomPattern(uint8_t array[], uint8_t length)
{
for (int i = 0; i < length; i++)
{
array[i] = rand() % 3;
}
}
void play(uint8_t pattern[])
{
uint8_t fullPattern[MAX_PATTERN_LENGTH];
createRandomPattern(fullPattern, MAX_PATTERN_LENGTH);
for (int i = 1; i <= MAX_PATTERN_LENGTH; i++)
{
printf("========LEVEL %d===========\n", i);
playPuzzle(fullPattern, i);
#ifdef DEBUG
printPuzzle(fullPattern, i);
#endif
readInput(fullPattern, i) ?: i--;
}
}
bool readInput(uint8_t pattern[], uint8_t length)
{
sei();
uint8_t current = 0;
while (current < length)
{
btnPushed = false;
while (!btnPushed)
{
}
cli();
if (currentPushed == pattern[current])
{
printf("correct, you pushed %d\n", currentPushed);
}
else
{
printf("incorrect, lets try again\n");
return false;
}
current++;
}
btnPushed = false;
return true;
}
void printPuzzle(uint8_t pattern[], uint8_t length)
{
printf("[ ");
for (int i = 0; i < length; i++)
{
printf("%d ", pattern[i]);
}
printf("]\n");
}
void playPuzzle(uint8_t pattern[], uint8_t length)
{
for (int i = 0; i < length; i++)
{
lightUpOneLed(pattern[i]);
_delay_ms(500);
lightDownOneLed(pattern[i]);
}
}
btnPushed is defined as bool btnPushed = false;.
So when you write:
while (!btnPushed)
{
#ifdef DEBUG
_delay_ms(1);
#endif
}
Nothing in the loop will change btnPushed so there is no point for the compiler to ever check btnPushed again. So what the compiler sees is this:
if (!btnPushed)
while(true)
{
#ifdef DEBUG
_delay_ms(1);
#endif
}
You have to tell the compiler that the value of btnPushed will change unexpectantly when the interrupt fires by using:
volatile bool btnPushed = false;

how can I read socket by blocking&none-multiplexing&sync mode?

I want to repeatedly request one specific url by maximum performance. I copied below source from github, but I think it isn't optimized for my case, so I have to tune it.
Which Option is best in my case?
block vs non-block
sync vs async
I think non-multiplexing is right, so I've to change select() function to the other one. Is this right?
char response[RESPONSE_SIZE + 1];
char *p = response, *q;
char *end = response + RESPONSE_SIZE;
char *body = 0;
enum {
length, chunked, connection
};
int encoding = 0;
int remaining = 0;
while (1) {
fd_set reads;
FD_ZERO(&reads);
FD_SET(server, &reads);
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 200;
if (FD_ISSET(server, &reads)) {
int bytes_received = SSL_read(ssl, p, end - p);
p += bytes_received;
*p = 0;
if (!body && (body = strstr(response, "\r\n\r\n"))) {
*body = 0;
body += 4;
printf("Received Headers:\n%s\n", response);
q = strstr(response, "\nContent-Length: ");
if (q) {
encoding = length;
q = strchr(q, ' ');
q += 1;
remaining = strtol(q, 0, 10);
} else {
q = strstr(response, "\nTransfer-Encoding: chunked");
if (q) {
encoding = chunked;
remaining = 0;
} else {
encoding = connection;
}
}
printf("\nReceived Body:\n");
}
if (body) {
if (encoding == length) {
if (p - body >= remaining) {
printf("%.*s", remaining, body);
break;
}
} else if (encoding == chunked) {
do {
if (remaining == 0) {
if ((q = strstr(body, "\r\n"))) {
remaining = strtol(body, 0, 16);
if (!remaining) goto finish;
body = q + 2;
} else {
break;
}
}
if (p - body >= remaining) {
printf("%.*s", remaining, body);
body += remaining + 2;
remaining = 0;
}
} while (!remaining);
}
} //if (body)
} //if FDSET
} //end while(1)
finish:
buffer[0] = '\0';
printf("\nClosing socket...\n");

TERMIOS C Program to communicate with STM32F103 µC

I am on stm32f103c8t6 with STDP-Lib, using stm32's usb library for virtual com port and wanna to talk with the µC via termios-Pc-program. The termios program can read the data the chip is sending via USB, but when I wanna answer, the chip is not reacting on the data I send. What am I doing wrong when sending?
The termios-program:
#include <stdio.h>
#include <unistd.h>
#include <termios.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
typedef union {
int num;
char part[2];
} _16to8;
static void sendData(int tty, unsigned char c) {
write(tty, &c, 1);
}
static unsigned char readData(int tty) {
unsigned char c;
while(read(tty, &c, 1) <= 0);
return c;
}
static unsigned char* readALotOfData(int tty, int len) {
unsigned char* c = NULL;
c = calloc(len, sizeof(unsigned char));
for(int i = 0; i < len; i++) {
c[i] = readData(tty);
}
return c;
}
static void sendCmd(int tty, char* c, size_t len) {
unsigned char* a = NULL;
int i = 0;
a = calloc(len, sizeof(unsigned char));
memcpy(a, c, len);
for(; i < len; i++) {
sendData(tty, a[i]);
}
free(a);
a = NULL;
}
int main(int argc, char** argv) {
struct termios tio;
int tty_fd;
FILE* fd;
struct stat st;
unsigned char c;
unsigned char* buf = NULL;
buf = calloc(4096, sizeof(unsigned char));
memset(&tio, 0, sizeof(tio));
tio.c_cflag = CS8;
tty_fd = open(argv[1], O_RDWR | O_NONBLOCK);
if(tty_fd == -1) {
printf("failed to open port\n");
return 1;
}
char mode;
if(!strcmp(argv[2], "flash")) {
mode = 1;
fd = fopen(argv[3], "r");
if(fd == NULL) {
printf("failed to open file\n");
return 1;
}
} else if(!strcmp(argv[2], "erase")) {
mode = 0;
} else {
printf("unknown operation mode\n");
return 1;
}
cfsetospeed(&tio, B115200);
cfsetispeed(&tio, B115200);
tcsetattr(tty_fd, TCSANOW, &tio);
unsigned char* id = readALotOfData(tty_fd, 20);
printf("%s\n", id);
if(strstr((const char*)id, "1234AABBCC1234")) {
sendCmd(tty_fd, "4321CCBBAA4321", 14);
printf("id verified\n");
} else {
printf("Could not identify device\n");
return 1;
}
if(mode) {
printf("going to flash the device\n");
sendCmd(tty_fd, "\xF1\xA5", 2);
stat(argv[3], &st);
int siz = st.st_size;
char sizR[2] = "\0";
sizR[1] = (unsigned char)(siz & 0xFF);
sizR[0] = (unsigned char)(siz >> 8);
_16to8 num = {0};
num.part[0] = sizR[0];
num.part[1] = sizR[1];
sendCmd(tty_fd, (char*)&num.num, 2);
char buffer[2] = {0};
int i = 0;
while(fread(&buffer, 1, 4, fd)) {
// sendCmd(tty_fd, buffer, 4);
// printf("%s\n", readALotOfData(tty_fd, 5));
}
} else {
printf("going to erase the device's memory\n");
sendCmd(tty_fd, (char*)0xE2A5, 2);
}
close(tty_fd);
return 0;
}
µCProgram:
#include "stm32f10x_conf.h"
#include "main.h"
void eraseFlashPage(uint8_t page) {
uint32_t addr = FLASH_ADDR + 0x400 * page;
FLASH_Unlock();
FLASH_ClearFlag(FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR | FLASH_FLAG_EOP);
FLASH_ErasePage(addr);
FLASH_Lock();
}
void writeFlashAddr(uint8_t page, uint16_t offset, uint32_t data) {
uint32_t addr = FLASH_ADDR + 0x400 * page + offset;
FLASH_Unlock();
FLASH_ClearFlag(FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR | FLASH_FLAG_EOP);
FLASH_ProgramWord(addr, (uint32_t)data);
FLASH_Lock();
}
uint32_t readFlashAddr(uint8_t page) {
uint32_t addr = FLASH_ADDR + 0x400 * page;
return *(uint32_t*)addr;
}
void TIM2_IRQHandler() {
static int count = 0;
if(TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET) {
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
if(mode) {
if(count == 2) {
count = 0;
GPIO_ToggleBits(GPIOA, GPIO_Pin_15);
}
count++;
} else {
GPIO_ToggleBits(GPIOA, GPIO_Pin_15);
}
}
}
int main() {
Set_System();
Set_USBClock();
USB_Interrupts_Config();
USB_Init();
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_PinRemapConfig(GPIO_Remap_SWJ_JTAGDisable, ENABLE);
GPIO_InitTypeDef gpioStruct;
gpioStruct.GPIO_Pin = GPIO_Pin_15;
gpioStruct.GPIO_Mode = GPIO_Mode_Out_PP;
gpioStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &gpioStruct);
GPIO_WriteBit(GPIOA, GPIO_Pin_15, Bit_RESET);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); // 200Hz -> 8Hz
TIM_TimeBaseInitTypeDef timStruct;
timStruct.TIM_Prescaler = 60000;
timStruct.TIM_CounterMode = TIM_CounterMode_Up;
timStruct.TIM_Period = 50; // ISR at 0.125s
timStruct.TIM_ClockDivision = TIM_CKD_DIV4;
timStruct.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM2, &timStruct);
TIM_Cmd(TIM2, ENABLE);
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
NVIC_InitTypeDef nvicStruct;
nvicStruct.NVIC_IRQChannel = TIM2_IRQn;
nvicStruct.NVIC_IRQChannelPreemptionPriority = 0;
nvicStruct.NVIC_IRQChannelSubPriority = 1;
nvicStruct.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&nvicStruct);
_delay_ms(500);
while(1) {
mode = 0;
Receive_length = 0;
char bootID[64];
for(volatile uint32_t cnt = 0; cnt < 4800 * 5000 / 4 / 25; cnt++) {
_printf("1234AABBCC1234");
CDC_Receive_DATA();
if(Receive_length >= 14) {
_gets((char*)&bootID, 14);
if(!memcmp(bootID, "4321CCBBAA4321", 14)) {
mode = 1;
break;
}
Receive_length = 0;
}
}
if(mode) {
uint32_t opt = 0;
_printf("operating mode?\n"); //debug
_gets((char*)&opt, 2);
if(opt == 0xF1A5) {
uint32_t len = 0;
uint32_t data = 0;
uint16_t i = 0;
_gets((char*)&len, 2);
_printf("writing %d/%d bytes starting at 0x%x\n", len, (117 - START_PAGE) * 1024, FLASH_ADDR); // debug
if(len < (117 - START_PAGE) * 1024) { // 117 or 64?
_printf("start writing to flash\n"); //debug
for(i = 0; i <= len / 1024; i++) {
eraseFlashPage(i);
_printf("erasing page %d\n", i); //debug
}
for(i = 0; i < len; i += 4) {
uint8_t page = i / 1024;
_printf("i:%d page:%d offset:%d\n", i, page, i - page * 1024); // debug
_gets((char*)&data, 4);
writeFlashAddr(page, i - page * 1024, data);
_printf("Page %d and 0x%x\n", page, FLASH_ADDR + 0x400 * page + i - page * 1024); // debug
}
_printf("done\n"); //debug
uint32_t sp = *(uint32_t*) FLASH_ADDR;
if((sp & 0x2FFF0000) == 0x20000000) {
TIM_Cmd(TIM2, DISABLE);
GPIO_WriteBit(GPIOA, GPIO_Pin_15, Bit_RESET);
NVIC->ICER[0] = 0xFFFFFFFF;
NVIC->ICER[1] = 0xFFFFFFFF;
NVIC->ICPR[0] = 0xFFFFFFFF;
NVIC->ICPR[1] = 0xFFFFFFFF;
PowerOff();
pFunction jmpUser;
uint32_t jmpAddr = *(__IO uint32_t*)(FLASH_ADDR + 4);
jmpUser = (pFunction)jmpAddr;
__set_MSP(*(__IO uint32_t*)FLASH_ADDR);
jmpUser();
}
} else {
_printf("not enought flash space available\n"); //debug
}
} else if(opt == 0xE2A5) {
for(int i = 0; i < (117 - START_PAGE); i++) {
eraseFlashPage(i);
_printf("erasing page %d\n", i); //debug
}
}
} else {
uint32_t sp = *(uint32_t*) FLASH_ADDR;
if((sp & 0x2FFF0000) == 0x20000000) {
TIM_Cmd(TIM2, DISABLE);
GPIO_WriteBit(GPIOA, GPIO_Pin_15, Bit_RESET);
NVIC->ICER[0] = 0xFFFFFFFF;
NVIC->ICER[1] = 0xFFFFFFFF;
NVIC->ICPR[0] = 0xFFFFFFFF;
NVIC->ICPR[1] = 0xFFFFFFFF;
PowerOff();
pFunction jmpUser;
uint32_t jmpAddr = *(__IO uint32_t*)(FLASH_ADDR + 4);
jmpUser = (pFunction)jmpAddr;
__set_MSP(*(__IO uint32_t*)FLASH_ADDR);
jmpUser();
}
}
}
}
I want to send the identification string and then enter the operations.... A friend of me got a working program with serialport-lib usage, but I wanna use termios...
Anyone an idea why the controller is not reacting on the sent data?

PIC32MX Controller UART1 receive not working

I am working with PIC32MX350F128L.The uart1 which is PIN 22 for (TX) and pin 20 for (RX). I am able to send a character but not able to receive any character.Below is the code attached.
Please do have a look at code and suggest some changes ?
void init_uart();
void UART1PutChar(unsigned char Ch);
char SerialReceive_1();
void main()
{
char res;
OSCCON=0x00002200; //ask settings clock
ANSELBbits.ANSB3 = 0;
ANSELBbits.ANSB5 = 0;
TRISCbits.TRISC3 = 0;
TRISCbits.TRISC4 = 0;
PORTCbits.RC3 = 1;
PORTCbits.RC4 = 1;
TRISBbits.TRISB3 = 0; //in controler tx
TRISBbits.TRISB5 = 1; // in controller RX
U1RXR=0x08;
RPB3R=0x03;
init_uart() ;
UART1PutChar('T');
while(1)
{
res = SerialReceive_1();
UART1PutChar(res);
}
}
void init_uart()
{
U1MODEbits.ON =1;
U1BRG = 25;
U1STA=0x1400;
IFS1bits.U1RXIF = 0;
IFS1bits.U1TXIF = 0 ;
return;
}
void UART1PutChar(unsigned char Ch)
{
while(U1STAbits.UTXBF == 1);
U1TXREG=Ch;
return ;
}
char SerialReceive_1()
{
char buf1;
while(!U1STAbits.URXDA);
buf1 = U1RXREG;
return buf1;
}
Regards

Resources