AVR controller, button issue - c

I have problem, microcontroller simply doesnt register when i press button. As it didnt happened. Here is my code.
#ifndef F_CPU
#define F_CPU 1000000UL
#endif
#define bit_is_clear(byte, bit) (!(byte & (1 << bit)))
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
typedef enum { false, true } boolean;
boolean clicked = false;
int sigurno_pritisnut = 0;
void pressed();
void unpressed();
int main(void)
{
//LED OUTPUT
DDRB |= (1 << PINB0) | (1 << PINB1) | (1 << PINB2);
//LED LOW
PORTB &= ~((1 << PINB0) | (1 << PINB1) | (1 << PINB2));
//BUTTON INPUT
DDRC &= ~(1 << PINC5);
//BUTTON HIGH
PORTC |= (1 << PINC5);
/* Replace with your application code */
while (1)
{
if(bit_is_clear(PINC, PINC5)){
sigurno_pritisnut++;
if(sigurno_pritisnut > 400){
clicked = !clicked;
sigurno_pritisnut = 0;
}
}
if(clicked){
pressed();
}else{
unpressed();
}
}
}
void pressed(){
PORTB ^= (1 << PINB0);
_delay_ms(500);
PORTB ^= (1 << PINB1);
_delay_ms(500);
PORTB ^= (1 << PINB2);
_delay_ms(500);
sigurno_pritisnut = 0;
}
void unpressed(){
PORTB ^= (1 << PINB0);
_delay_ms(500);
PORTB ^= (1 << PINB0);
PORTB ^= (1 << PINB1);
_delay_ms(500);
PORTB ^= (1 << PINB1);
PORTB ^= (1 << PINB2);
_delay_ms(500);
PORTB ^= (1 << PINB2);
}
...................................................................
I have tried with other buttons, tried with other pins but nothing.
...................................................................

The problem seem to be your delay statements. In both pressed and unpressed you wait 3 x 500ms.
In the loop you want to see bit_is_clear 400 times before changing clicked.
So it seems that bit_is_clear must be true in 600 seconds before you change clicked.
Notice that this
if(clicked){
pressed();
}else if(!clicked){
unpressed();
}
is the same as
if(clicked){
pressed();
}else
unpressed();
}
so in every loop you'll enter one of them.
Further it seems strange that you don't an else here:
if(bit_is_clear(PINC, PINC5)){
sigurno_pritisnut++;
if(sigurno_pritisnut > 500){
clicked = !clicked;
sigurno_pritisnut = 0;
}
}
else
{
// ... don't you need some code here?
}
So button works like this
bit_is_clear == true means pressed
bit_is_clear == false means released
you'll need something like:
while (1)
{
while (1) // Loop until a state is changed
{
if(bit_is_clear(PINC, PINC5))
{
// pressed
if (clicked)
{
// Same state so just continue...
sigurno_pritisnut = 0;
continue;
}
sigurno_pritisnut++;
if(sigurno_pritisnut > 400){
clicked = 1;
sigurno_pritisnut = 0;
// State change - break out
break;
}
}
else
{
// released
if (!clicked)
{
sigurno_pritisnut = 0;
continue;
}
sigurno_pritisnut++;
if(sigurno_pritisnut > 400){
clicked = 0;
sigurno_pritisnut = 0;
break;
}
}
}
if(clicked){
pressed();
}else{
unpressed();
}
}
In this way you only call pressed / unpressed when something new has happened.

Related

How to get GPS Data when switch is pressed in Atmega328p

So I am working on getting the gps data when the button is pressed using external interrupt. My problem is , it is working without the external interrupt but when I added it, it's not getting the data. Is something wrong with my code? I am using quectel l80-m39 for gps connected to the rx of atmega328p. Provided below is my code. The button is connected to PD3 of atmega.
#define F_CPU 8000000UL // Defining the CPU Frequency
#include <avr/io.h> // Contains all the I/O Register Macros
#include <util/delay.h> // Generates a Blocking Delay
#include <avr/interrupt.h>
#define USART_BAUDRATE 9600 // Desired Baud Rate
#define BAUD_PRESCALER (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)
void USART_Init()
{
// Set Baud Rate
UBRR0H = (unsigned char)(BAUD_PRESCALER >> 8);
UBRR0L = (unsigned char)BAUD_PRESCALER;
// Enable Receiver
UCSR0B |= (1 << RXEN0);
// Set data frame format: asynchronous mode,no parity, 1 stop bit, 8 bit size
UCSR0C |= (1 << UCSZ01) | (1 << UCSZ00);
}
unsigned char USART_ReceivePolling(void)
{
while (!(UCSR0A & (1 << RXC0)));
return UDR0;
}
void readgps()
{
uint8_t lati_value[15];
unsigned char LocalData;
int i = 0;
LocalData = USART_ReceivePolling();
if (LocalData == '$')
{
LocalData = USART_ReceivePolling();
if (LocalData == 'G')
{
LocalData = USART_ReceivePolling();
if (LocalData == 'P')
{
LocalData = USART_ReceivePolling();
if (LocalData == 'G')
{
LocalData = USART_ReceivePolling();
if (LocalData == 'G')
{
LocalData = USART_ReceivePolling();
if (LocalData == 'A')
{
LocalData = USART_ReceivePolling();
if (LocalData == ',')
{
LocalData = USART_ReceivePolling();
while (LocalData != ',')
{
LocalData = USART_ReceivePolling();
}
LocalData = USART_ReceivePolling();
while (LocalData != ',')
{
lati_value[i] = LocalData;
++i;
LocalData = USART_ReceivePolling();
}
PORTD |= (1 << PD2);
_delay_ms(100);
}
}
}
}
}
}
} else
{
PORTD &= ~(1 << PD2);
}
}
int main(void)
{
EICRA |= (1 << ISC10) | (1 << ISC11); // interrupt on rising edge of INT1
EIMSK |= (1 << INT1); // external interrupt enable on INT1
sei();
while (1)
{
}
}
ISR(INT1_vect)
{
if (PIND & (1 << 3))
{
DDRD = 0b01110110;
USART_Init();
readgps();
}
}
USART_ReceivePolling() is blocking the ISR. You should never block the ISR. In the ISR just set a flag and check it in the main loop. Something like this (unchanged code removed):
// ...
// Flag for reading the GPS
volatile unsigned char g_read_gps = 0;
// ...
int main(void)
{
// ...
while (1)
{
if (g_read_gps) {
readgps();
g_read_gps = 0;
}
}
}
ISR(INT1_vect)
{
if (PIND & (1 << 3))
{
g_read_gps = 1;
}
}

How can I reduce the size of my code and get the same result

Is there a way to get the same result with a smaller size of code in c?
My Function:
void PCA9575_set_gpio_level(uint8_t gpio_num, uint8_t level) {
uint8_t reg, data, pin;
uint8_t buf[1] = {0};
buf[1] = PCA9575_read_register(OUT0);
if (gpio_num >= 28 && gpio_num <= 35) {
reg = OUT0;
pin = gpio_num - 27;
if (pin == 3) {
pin = 4;
} else if (pin == 4) {
pin = 8;
} else if (pin == 5) {
pin = 16;
} else if (pin == 6) {
pin = 32;
} else if (pin == 7) {
pin = 64;
} else if (pin == 8) {
pin = 128;
} else {
return;
}
if (level == 1) {
if (buf[1] == 0) {
data = pin;
} else if (buf[1] == 0xFF) {
data = 0xFF;
} else {
data = buf[1] ^ pin;
}
} else if (level == 0) {
if (buf[1] == 0) {
data = 0;
} else {
data = buf[1] ^ pin;
}
} else {
return;
}
}
else if (gpio_num >= 36 && gpio_num <= 43) {
reg = OUT1;
pin = gpio_num - 35;
if (pin == 3) {
pin = 4;
} else if (pin == 4) {
pin = 8;
} else if (pin == 5) {
pin = 16;
} else if (pin == 6) {
pin = 32;
} else if (pin == 7) {
pin = 64;
} else if (pin == 8) {
pin = 128;
} else {
return;
}
if (level == 1) {
if (buf[1] == 0) {
data = pin;
} else {
data = buf[1] ^ pin;
}
} else if (level == 0) {
if (buf[1] == 0) {
data = 0;
} else {
data = buf[1] ^ pin;
}
} else {
return;
}
}
else {
return;
}
PCA9575_write_to_register(reg, data);
}
The buf[1] variable is a value from 00000000 - 11111111 which is based on what has already been set.
The data variable is a value from 00000000 - 11111111 which will set the gpio pins.
The code should read what gpio pins are set and keep them set. Also at the same time set the new desired gpio pin.
GPIO pins are values from 28 - 43.
maybe:
void PCA9575_set_gpio_level(uint8_t gpio_num, uint8_t level)
{
uint8_t reg, pin;
uint8_t buf = PCA9575_read_register(OUT0);
if (gpio_num > 27 && gpio_num < 36)
{
reg = OUT0;
pin = gpio_num - 27;
}
else
{
if (gpio_num > 35 && gpio_num < 44)
{
reg = OUT1;
pin = gpio_num - 35;
}
}
else return;
pin = 1 << (pin - 1);
if(level < 2)
{
if(!buf) data = level * pin;
else if(buf == 0xff && gpio_num < 36) data = 0xff;
else data = buf ^pin;
}
PCA9575_write_to_register(reg, data);
}

I'm trying to make a morse code transmitter with the AtMega 32u4, but the microprocessor dosen't sees my input buttons and i don't know why?

I have an Adafruit feather 32u4 LoRa transmitter, I want to make a digital Morse transmitter, I took the transmission code from the internet and decided to write my own code for the rest. The two transistors transmit to each other but the micro don sees my input buttons.
int StatoPrecP2 = 0;
int i;
char SendData;
void loop()
{
switch (Stato) {
StatoAttP1 = digitalRead(P_Riga);
StatoAttP2 = digitalRead (P_Punto);
case 0:
if (StatoAttP1 == 1) /*&& (StatoPrecP1 != StatoAttP1 )) */{
digitalWrite(ButtonRecived, HIGH);
delay (250);
digitalWrite(ButtonRecived, LOW);
Stato = 1;
SendData = ".";
}
if ((StatoAttP2 == 1) && (StatoPrecP2 != StatoAttP1)) {
digitalWrite(ButtonRecived, 1);
delay (250);
digitalWrite(ButtonRecived, 0);
Stato = 1;
SendData = "-";
}
if (rf95.available())
{
// Should be a message for us now
uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
uint8_t len = sizeof(buf);
if (rf95.recv(buf, &len))
{
digitalWrite(LED, HIGH);
RH_RF95::printBuffer("Received: ", buf, len);
Serial.print("Got: ");
Serial.println((char*)buf);
Serial.print("RSSI: ");
Serial.println(rf95.lastRssi(), DEC);
if (*buf = ".") {
PORTF = PORTF | 0x20;
delay(1000);
PORTF = PORTF & ~0x20;
}
else if (*buf = "-") {
PORTF = PORTF | 0x20;
delay(2500);
PORTF = PORTF & ~0x20;
}
}
else
{
Serial.println("Receive failed");
}
case 1:
// Send a reply
for (i = 0; i < 5000; i++) {
uint8_t data = SendData;
rf95.send(data, sizeof(data));
rf95.waitPacketSent();
Serial.println("Sent a reply");
digitalWrite(LED, LOW);
if ((StatoAttP1 = 1) & (StatoAttP1 != StatoPrecP1)) {
PORTF = PORTF | 0x10;
delay (250);
PORTF = PORTF & ~0x10;
Stato = 1;
uint8_t data[] = ".";
i = 0;
}
else if ((StatoAttP2 = 1) & (StatoAttP2 != StatoPrecP2)) {
PORTF = PORTF | 0x10;
delay (250);
PORTF = PORTF & ~0x10;
Stato = 1;
uint8_t data[] = "-";
i = 0;
}
delay (1);
}
Stato = 0;
}
}
StatoPrecP1 = StatoAttP1;
StatoPrecP2 = StatoAttP2;
}
While it's allowed to put statements inside a switch that still are outside any case, those will simply not be executed.
You have:
switch (Stato) {
StatoAttP1 = digitalRead(P_Riga);
StatoAttP2 = digitalRead (P_Punto);
case 0:
But the two digitalRead calls will never happen, which is the source of your problem.
You need to place those statements outside the switch:
StatoAttP1 = digitalRead(P_Riga);
StatoAttP2 = digitalRead (P_Punto);
switch (Stato) {
case 0:
A decent compiler should be able to warn about this problem, and if not you need to enable more warnings. And you should treat those warnings as errors the must be fixed.

creating a program and getting these errors

Can any one help with the errors im receiving
c55 error:general error
c55 error:faliure
I'm trying to compile the code and these are the errors im receiving and I dont know how to correct them at all
failed to locate output file 'pic control 1.obj'
#include <system.h>
#include <stdio.h>
unsigned char state, nxtstate, inbyte,g1,g2;
void checkS1S2()
{
inbyte=porta;
if ((inByte & 0x0F) == 0x07) //70%
{
nextstate =1; // turn on G1
}
if ((inByte & 0xF0) == 0x20) // 50%
{
nextstate =2; // turn on G2
}
if ((inByte & 0xF0) == 0xFF) // 100%
{
nextstate =3; // turn on G1 and G2
}
if (((inByte & 0xF0) == 0x00) || ((inByte & 0xF0) == 0x01))
{
nextState = 4; // TurnoFF G2
}
if (((inByte & 0x0F) == 0x00) || ((inByte & 0x0F) == 0x01) || ((inByte & 0x0F) == 0x02) )
{
nextState = 5; // TurnoFF G1
}
}
void state1(void)
{
bitset(portb1); // switch on G1
nextstate = 1;
g1 =1;
}//end of state1.
void state2(void)
{
bitset(portb2); // switch on G2
nextstate = 1;
g2 =1;
}//end of state2
void state3(void)
{
checktime;
{
if time up && (g1 ==1) && (g2 ==1);
state6;
else
state1;
}
}
void state6(void)
{
// switch OFF G0,G1,G2
bitclear(portb,0);
bitclear(portb,1);
bitclear(portb,2);
bitset(portb3);
nextstate = 1;
g1 =0;
g2=0;
}//end of state6
void state4(void)
{
bitclear(portb,1); // Switch OFF G1
nextstate =1;
g1 =0;
}
void state5()
{
bitclear(portb,2); // Switch OFF G2
g2 =0;
}
int main(void)
{
// Configure RA0-RA3 as S1 , RA4-RA7 as S2
// Configure RB0 as G0 , RB1 as G1 , RB2 as G2 and RB3 as LED
config();
nxtstate=0;
}
Your function state3 contains line that are not valid C code:
void state3(void)
{
checktime;
{
if time up && (g1 ==1) && (g2 ==1);
state6;
else
state1;
}
}
I assume that your intention was to add a comment and to invoke functions. In thart case you should do this:
void state3(void)
{
/* checktime */
{
if time up && (g1 ==1) && (g2 ==1);
state6();
else
state1();
}
}
Probably the checktime should be an boolean expression:
void state3(void)
{
if (checktime)
{
if time up && (g1 ==1) && (g2 ==1);
state6();
else
state1();
}
}
As you can see, the question left enough room for guessing.

glibc detected realloc(): invalid pointer

Im constantly getting this when I build on Qtcreator.
*** glibc detected *** /home/Exxamples/EffectivCons: realloc(): invalid pointer: 0xb6fb5414 ***
======= Backtrace: =========
/lib/i386-linux-gnu/libc.so.6(+0x75ee2)[0xb6603ee2]
/lib/i386-linux-gnu/libc.so.6(realloc+0x25d)[0xb660856d]
/lib/i386-linux-gnu/libc.so.6(realloc+0x273)[0xb6608583]
/opt/Qt5.1.1/5.1.1/gcc/lib/libQt5Core.so.5(_ZN9QListData7reallocEi+0x37)[0xb6906e67]
/opt/Qt5.1.1/5.1.1/gcc/lib/libQt5Core.so.5(_ZN9QListData6appendEi+0x7c)[0xb6906f4c]
/opt/Qt5.1.1/5.1.1/gcc/lib/libQt5Core.so.5(_ZN9QListData6appendEv+0x23)[0xb6906fd3]
/opt/Qt5.1.1/5.1.1/gcc/lib/libQt5Core.so.5(+0x1afa3e)[0xb6a05a3e]
/opt/Qt5.1.1/5.1.1/gcc/lib/libQt5Core.so.5(_Z21qRegisterResourceDataiPKhS0_S0_+0x216)[
This is my code, through the other questions on the website, I saw some users using malloc or realloc, but Im not using it, why am i getting an error?
#include <termios.h>
#include <string.h>
#include <stdlib.h>
#define BUFLEN 512
std::string numberToString(const int n);
void sendExpressivAnimation(int,EmoStateHandle eState);
void handleExpressivEvent(std::ostream& os, EmoEngineEventHandle expressivEvent);
bool handleUserInput();
void promptUser();
void nonblocking();
int getch();
int kbhit();
int createSocket();
int startSendPort = 30000;
struct termios initial_settings, new_settings;
int kbhit (void)
{
struct timeval tv;
fd_set rdfs;
tv.tv_sec = 0;
tv.tv_usec = 0;
FD_ZERO(&rdfs);
FD_SET (STDIN_FILENO, &rdfs);
select(STDIN_FILENO+1, &rdfs, NULL, NULL, &tv);
return FD_ISSET(STDIN_FILENO, &rdfs);
}
int main(int argc, char **argv)
{
EmoEngineEventHandle eEvent = EE_EmoEngineEventCreate();
EmoStateHandle eState = EE_EmoStateCreate();
unsigned int userID = 0;
const int CONTROL_PANEL_PORT = 3008;
bool connected = false;
if(EE_EngineRemoteConnect("127.0.0.1", CONTROL_PANEL_PORT)== EDK_OK)
{
std::cout <<"Emotiv Engine started" << std::endl;
connected = true;
}
else
{
std::cout <<"Emotiv Engine failed !"<< std::endl;
connected = false;
}
std::cout << "Type \"exit\" to quit, \"help\" to list available commands..." << std::endl;
promptUser();
int _socket;
_socket = createSocket();
if(connected)
{
nonblocking();
fflush(stdin);
while (true) {
// Handle the user input
//if (_kbhit()) {
if (!handleUserInput()) {
break;
}
//}
int state = EE_EngineGetNextEvent(eEvent);
// New event needs to be handled
if (state == EDK_OK) {
EE_Event_t eventType = EE_EmoEngineEventGetType(eEvent);
EE_EmoEngineEventGetUserId(eEvent, &userID);
switch (eventType) {
// New headset connected, create a new socket to send the animation
case EE_UserAdded:
{
std::cout << std::endl << "New user " << userID << " added, sending Expressiv animation to ";
std::cout << "127.0.0.1" << ":" << startSendPort << "..." << std::endl;
promptUser();
break;
}
// Headset disconnected, remove the existing socket
case EE_UserRemoved:
{
std::cout << std::endl << "User " << userID << " has been removed." << std::endl;
promptUser();
break;
}
// Send the Expressiv animation if EmoState has been updated
case EE_EmoStateUpdated:
{
//std::cout << "New EmoState from user " << userID << "..." << std::endl;
EE_EmoEngineEventGetEmoState(eEvent, eState);
sendExpressivAnimation(_socket,eState);
break;
}
// Handle Expressiv training event
case EE_ExpressivEvent:
{
handleExpressivEvent(std::cout, eEvent);
break;
}
default:
break;
}
}
else if (state != EDK_NO_EVENT) {
std::cout << std::endl << "Internal error in Emotiv Engine!" << std::endl;
break;
}
}
}
EE_EngineDisconnect();
EE_EmoStateFree(eState);
EE_EmoEngineEventFree(eEvent);
return 0;
}
std::string numberToString(const int n) {
char* buf;
//_itoa(n, buf, 10);
QString nStr = QString::number(n);
buf = nStr.toLocal8Bit().data();
return std::string(buf);
}
void sendExpressivAnimation(int _socket,EmoStateHandle eState) {
std::ostringstream output;
EE_ExpressivAlgo_t upperFaceType = ES_ExpressivGetUpperFaceAction(eState);
EE_ExpressivAlgo_t lowerFaceType = ES_ExpressivGetLowerFaceAction(eState);
float upperFaceAmp = ES_ExpressivGetUpperFaceActionPower(eState);
float lowerFaceAmp = ES_ExpressivGetLowerFaceActionPower(eState);
if (ES_ExpressivIsBlink(eState)) {
output << "B,";
}
if (ES_ExpressivIsLeftWink(eState)) {
output << "l,";
}
if (ES_ExpressivIsRightWink(eState)) {
output << "r,";
}
if (ES_ExpressivIsLookingRight(eState)) {
output << "R,";
}
if (ES_ExpressivIsLookingLeft(eState)) {
output << "L,";
}
if (upperFaceAmp > 0.0) {
switch (upperFaceType) {
case EXP_EYEBROW: output << "b"; break;
case EXP_FURROW: output << "f"; break;
default: break;
}
output << numberToString(static_cast<int>(upperFaceAmp*100.0f)) << ",";
}
if (lowerFaceAmp > 0.0) {
switch (lowerFaceType) {
case EXP_CLENCH: output << "G"; break;
case EXP_SMILE: output << "S"; break;
case EXP_LAUGH: output << "H"; break;
case EXP_SMIRK_LEFT: output << "sl"; break;
case EXP_SMIRK_RIGHT: output << "sr"; break;
default: break;
}
output << numberToString(static_cast<int>(lowerFaceAmp*100.0f)) << ",";
}
std::string outString = output.str();
// Remove the last comma
if (outString.length()) {
outString.resize(outString.length()-1);
}
if (!outString.length()) {
outString = std::string("neutral");
}
if(send(_socket, outString.c_str(), BUFLEN, 0)==-1)
{
std::cout<<"sending error"<<std::endl;
//exit(1);
}
}
void handleExpressivEvent(std::ostream& os, EmoEngineEventHandle expressivEvent) {
unsigned int userID = 0;
EE_EmoEngineEventGetUserId(expressivEvent, &userID);
EE_ExpressivEvent_t eventType = EE_ExpressivEventGetType(expressivEvent);
switch (eventType) {
case EE_ExpressivTrainingStarted:
{
os << std::endl << "Expressiv training for user " << userID << " STARTED!" << std::endl;
break;
}
case EE_ExpressivTrainingSucceeded:
{
os << std::endl << "Expressiv training for user " << userID << " SUCCEEDED!" << std::endl;
break;
}
case EE_ExpressivTrainingFailed:
{
os << std::endl << "Expressiv training for user " << userID << " FAILED!" << std::endl;
break;
}
case EE_ExpressivTrainingCompleted:
{
os << std::endl << "Expressiv training for user " << userID << " COMPLETED!" << std::endl;
break;
}
case EE_ExpressivTrainingDataErased:
{
os << std::endl << "Expressiv training data for user " << userID << " ERASED!" << std::endl;
break;
}
case EE_ExpressivTrainingRejected:
{
os << std::endl << "Expressiv training for user " << userID << " REJECTED!" << std::endl;
break;
}
case EE_ExpressivTrainingReset:
{
os << std::endl << "Expressiv training for user " << userID << " RESET!" << std::endl;
break;
}
case EE_ExpressivNoEvent:
default:
//## unhandled case
assert(0);
return;
}
promptUser();
}
bool handleUserInput() {
static std::string inputBuffer;
char c = getch();
if ((int)c == 10) {
std::cout << std::endl;
std::string command;
const size_t len = inputBuffer.length();
command.reserve(len);
// Convert the input to lower case first
for (size_t i=0; i < len; i++) {
command.append(1, tolower(inputBuffer.at(i)));
}
inputBuffer.clear();
bool success = parseCommand(command, std::cout);
promptUser();
return success;
}
else {
if ((int)c == 127) { // Backspace key
if (inputBuffer.length()) {
putchar('\b');
putchar(' ');
putchar('\b');
inputBuffer.erase(inputBuffer.end()-1);
}
}
else {
std::cout << c;
if(((int) c == 32) || ((int)c == 95) || (((int)c >= 97 && (int)c <=122)) || (((int)c >=48 && (int)c <= 57)))
inputBuffer.append(1,c);
}
}
return true;
}
void promptUser()
{
std::cout << "ExpressivDemo> "<<std::endl;
}
void nonblocking()
{
tcgetattr(0, &initial_settings);
new_settings = initial_settings;
new_settings.c_lflag &= ~ICANON;
new_settings.c_lflag &= ~ECHO;
//new_settings.c_lflag &= ~ISIG;
new_settings.c_cc[VMIN] = 0;
new_settings.c_cc[VTIME] = 0;
tcsetattr(0, TCSANOW, &new_settings);
}
int getch()
{
int r;
unsigned char c=0;
if((r = read(0, &c, sizeof(c))) < 0 )
{
return r;
}
else
{
return c;
}
}
int createSocket()
{
struct sockaddr_in si_other;
int s, slen = sizeof(si_other);
if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
std::cout<<"socket"<<std::endl;
memset((char *) &si_other, 0, sizeof(si_other));
si_other.sin_family = AF_INET;
si_other.sin_port = htons(startSendPort);
if (inet_aton("127.0.0.1", &si_other.sin_addr)==0)
{
std::cout<<"intet_aton failed !"<<std::endl;
//exit(1);
}
if(connect(s,(sockaddr*)&si_other,slen)==-1)
{
std::cout<<"connect failed !"<<std::endl;
// exit(1);
}
return s;
}
Your code is too big to be checked wholly. If you can reduce it to a SSCCE it will be easier for everybody.
Anyway, skimming over your code, only one thing catched my eye:
char *buf;
QString nStr = QString::number(n);
buf = nStr.toLocal8Bit().data();
return std::string(buf);
The call to toLocal8Bit() returns a temporary QByteArray and then you call its data() member function. The returned pointer is only valid during the lifetime of that temporary, that is, until the ending ;. After that the buf pointer is invalid and the next line renders undefined behavior.
You should do something like:
QString nStr = QString::number(n);
QByteArray a(nStr.toLocal8Bit());
char *buf = a.data();
return std::string(buf);
Or even better:
QString nStr = QString::number(n);
return std::string(nStr.toLocal8Bit().data());
Or just for show:
return std::string(QString::number(n).toLocal8Bit().data());

Resources