barcode reader for Arduino recognize char - arrays

I have a barcode code but need it to recognize the barcode so it can print to serial monitor. I have searched that I need to have it convert to int from char but have yet to find a way to do that if that is the answer.
For example I scan a barcode and if it is a certain number, then the serial monitor will print it.
#include <hid.h>
#include <hiduniversal.h>
#include <usbhub.h>
#include <Usb.h>
#include <hidboot.h>
#include <avr/pgmspace.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Bridge.h>
#include <FileIO.h>
#include <TM1637Display.h>
#define DEBUG true
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
const byte BarcodeLength = 11;
const int buzzer = 2;
const int CLK = 9; //Set the CLK pin connection to the display
const int DIO = 8; //Set the DIO pin connection to the display
const int DIO2 = 7; // Set 2nd DIO pin to second connection to display
const int CLK2 = 6; // Set the 2nd CLK pin to the second connection to display.
const int procTime = 5; // this is the time it takes for the process to finish countdown
int NumStep = 0; //Variable to interate
TM1637Display countdownDisplay(CLK, DIO); //set up the 4-Digit Display.
TM1637Display DelayedDisplay(CLK2, DIO2); //set up the 4-Digit Display.
class BarcodeReader : public KeyboardReportParser
{
USB Usb;
USBHub Hub;
HIDUniversal Hid;
HIDBoot<HID_PROTOCOL_KEYBOARD> Keyboard;
uint8_t buffer[15];
byte length;
bool valid;
void addCharacter(uint8_t c);
public:
BarcodeReader();
void begin();
void task();
const uint8_t* barcode();
void reset();
protected:
virtual void OnKeyDown(uint8_t mod, uint8_t key);
};
BarcodeReader::BarcodeReader()
: Usb()
, Hub(&Usb)
, Hid(&Usb)
, Keyboard(&Usb)
, length(0)
, valid(false)
{
}
void BarcodeReader::begin()
{
if (Usb.Init() == -1) {
Serial.println("OSC did not start.");
}
else
Serial.println("Barcode Ready");
Hid.SetReportParser(1, this);
}
void BarcodeReader::task()
{
Usb.Task();
}
void BarcodeReader::addCharacter(uint8_t c)
{
if (valid) {
// already have a barcode, new one will overwrite it
reset();
}
// could check for \n or \r if necessary, or even implement a timing
// mechanism for detecting end of barcode input, but for now we just
// assume fixed width field with no output separators
buffer[length++] = c;
//buffer[length] = '\0';
if (buffer[length] == '\0')
{
valid = true;
}
};
// return value no longer valid after another call to task()
const uint8_t* BarcodeReader::barcode()
{
return (valid) ? buffer : 0;
}
void BarcodeReader::reset()
{
length = 0;
valid = false;
}
void BarcodeReader::OnKeyDown(uint8_t mod, uint8_t key) {
uint8_t c = OemToAscii(mod, key);
if (c) addCharacter(c);
}
BarcodeReader barcodeReader;
void setup() {
countdownDisplay.showNumberDec(0);
DelayedDisplay.showNumberDec(0);
Bridge.begin();
Console.begin();
FileSystem.begin();
Serial.begin(9600);
if (DEBUG) Console.println("Done setup");
lcd.begin(16, 2);
pinMode(buzzer,OUTPUT);
//Serial.begin(115200);
lcd.print("Please Scan Your ID: ");
barcodeReader.begin();
countdownDisplay.setBrightness(0x0a); //set the diplay to maximum brightness
DelayedDisplay.setBrightness(0x0a);
}
void loop() {
//char *goodCards = { "1234567" };
//String dataString = "Testing, 1, 2, 3...";
File dataFile = FileSystem.open("/mnt/sda1/datalog.txt", FILE_APPEND);
// If the file opens successfully, write the string to it, close the file,
// and print the information to the Serial monitor.
barcodeReader.task();
const char* barcode = barcodeReader.barcode();
if (barcode || dataFile) {
lcd.print(barcode);
dataFile.print(barcode);
Serial.print(barcode);
barcodeReader.reset();
dataFile.close();
//If the barcode is the word 'Setup' then print setup to the screen
//search array of char conver strcmp(). You are sending 0101 not the actual value of 1234567
// collect all the input, convert it to an int
if(barcode == "0001") {
{
Serial.println(": SETUP");
}
}
}
//timer and barcode
//
// if(barcode == "1234567") {
// Serial.print(barcode);
// Serial.println(": SETUP");
//
//// analogWrite(A1,0);
//// analogWrite(A2,0);
// }
// if(barcode == "KAYAMAD") {
// Serial.print(barcode);
// Serial.println(": RUN");
//
//// analogWrite(A0,0);
//// analogWrite(A2,0);
// countdownDisplay.showNumberDec(0);
// DelayedDisplay.showNumberDec(0);
// for(int NumStep = procTime; NumStep > 0 ; NumStep--) //Interrate NumStep
// {
// countdownDisplay.showNumberDec(NumStep); //Display the Variable value;
// //DelayedDisplay.showNumberDec(NumStep); //Display the Variable value;
// delay(1000); //A second delay between steps.
// }
//
// for (int NumStep = 0; NumStep < 5 ; NumStep++) //Interrate NumStep
// {
// //countdownDisplay.showNumberDec(NumStep); //Display the Variable value;
// DelayedDisplay.showNumberDec(NumStep); //Display the Variable value;
// countdownDisplay.showNumberDec(0);
// delay(1000); //A second delay between steps.
//
// }
//
// }
//
// else if (barcode == "2234663") {
// Serial.print(barcode);
// Serial.println(": DELAY");
//
//// analogWrite(A0,0);
//// analogWrite(A1,0);
// countdownDisplay.showNumberDec(0);
// DelayedDisplay.showNumberDec(0);
//
//
// for (int NumStep = 0; NumStep < 5 ; NumStep++) //Interrate NumStep
// {
// //countdownDisplay.showNumberDec(NumStep); //Display the Variable value;
// DelayedDisplay.showNumberDec(NumStep); //Display the Variable value;
// countdownDisplay.showNumberDec(0);
// delay(1000); //A second delay between steps.
//
// }
//
//
// }
//
// If there is a problem opening the file, send an error to the Serial monitor
else {
if (DEBUG) Console.println("Error opening datalog.txt");
}
}

"Number" you get Computer sees as text, not number. We are sure that barcode will always be number. Conver char to int with atoi function.
Here's an example:
const char *bar = "123";
int bc = atoi(bar);

Related

how to create condition using ros odom pose data?

I have a mobile autonomous robot that moves using Ros. My goal is to communicate with rosserial via arduino and subscribe to the odom topic. I would like to put some conditions on the exposure data I received after I became a member of Odom. In order to be able to perform some operations at certain points in the coordinates on my map. with a simple example
if (pose_x>2.17 &&pose_x<4.00 &&pose_y<7.6 &&pose_y>9.5 ){
digitalWrite(led_pin, HIGH - digitalRead(13));
}
I want to add conditions like but I don't know how to do that. I'm not very good at software.Below is the code I am trying to do with arduino. I may have been a little silly. I'm still very lacking. I will be grateful for all your help.
#include <ros.h>
#include <std_msgs/String.h>
#include <nav_msgs/Odometry.h>
#include <geometry_msgs/Twist.h>
#include <tf/transform_broadcaster.h>
#include <tf/tf.h>
ros::NodeHandle nh;
ros::Time current_time;
float TIME;
float pose_x, pose_y, angle_z;
geometry_msgs::Quaternion odom_quat;
tf::TransformBroadcaster odom_broadcaster;
std_msgs::String message;
ros::Publisher server_pub("/server_messages", &message);
const int button1_pin = 6;
const int button2_pin = 7;
const int led_pin = 13;
char button1[13] = "2";
char button2[13] = "3";
bool last_reading1;
long last_debounce_time1 = 0;
bool last_reading2;
long last_debounce_time2 = 0;
long debounce_delay = 50;
bool published1 = true;
bool published2 = true;
void odomCallback(const nav_msgs::Odometry & msg) {
nav_msgs::Odometry odom;
odom.header.stamp = current_time;
geometry_msgs::TransformStamped odom_trans;
odom_trans.header.stamp = current_time;
odom_trans.transform.translation.x = pose_x;
odom_trans.transform.translation.y = pose_y;
odom_trans.transform.translation.z = 0.0;
odom_trans.transform.rotation = odom_quat;
odom.pose.pose.position.x = pose_x;
odom.pose.pose.position.y = pose_y;
odom.pose.pose.position.z = 0.0;
odom.pose.pose.orientation = odom_quat;
if (pose_x>-8 && pose_x<10 && pose_y>-8 && pose_y<8) {
digitalWrite(led_pin, HIGH - digitalRead(13));
}
else {
digitalWrite(led_pin, LOW - digitalRead(13));
}
}
ros::Subscriber <nav_msgs::Odometry> sub("/odom", odomCallback);
void setup()
{
nh.initNode();
nh.advertise(server_pub);
nh.subscribe(sub);
//initialize an LED output pin
//and a input pin for our push button
pinMode(led_pin, OUTPUT);
pinMode(button1_pin, INPUT);
pinMode(button2_pin, INPUT);
//Enable the pullup resistor on the button
digitalWrite(button1_pin, HIGH);
digitalWrite(button2_pin, HIGH);
//The button is a normally button
last_reading1 = ! digitalRead(button1_pin);
last_reading2 = ! digitalRead(button2_pin);
}
void loop()
{
bool reading1 = ! digitalRead(button1_pin);
bool reading2 = ! digitalRead(button2_pin);
if (last_reading1 != reading1) {
last_debounce_time1 = millis();
published1 = false;
}
if (last_reading2 != reading2) {
last_debounce_time2 = millis();
published2 = false;
}
//if the button value has not changed for the debounce delay, we know its stable
if ( !published1 == 1 && (millis() - last_debounce_time1) > debounce_delay) {
digitalWrite(led_pin, reading1);
message.data = button1 ;
server_pub.publish(&message);
published1 = true;
}
if ( !published2 == 1 && (millis() - last_debounce_time2) > debounce_delay) {
digitalWrite(led_pin, reading2);
message.data = button2 ;
server_pub.publish(&message);
published2 = true;
}
last_reading1 = reading1;
last_reading2 = reading2;
nh.spinOnce();
}
It seems like you're not using the data from the odomCallback at all.
Looks like pose_x and pose_y values never get set. Try adding this to the beginning of the odomCallback function (not tested):
// set pose_x and pose_y to their most recent values
pose_x = msg.pose.pose.position.x;
pose_y = msg.pose.pose.position.y;

Saving Custum Paramter with WifiManager & Arduinojson 6

I'm trying to save an additional custom parameter to wifimanager which is the mqtt server address but all codes available in the library and all over the internet are for Arduinojson 5, I tried upgrading to Arduinojson 6 to the best of my ability. The code runs with no issues, however, when I restart the esp, it is gone. For somereason, it is not saved.
#include <FS.h> //this needs to be first, or it all crashes and burns...
#include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
#include <ArduinoJson.h> //https://github.com/bblanchon/ArduinoJson
#define TRIGGER_PIN 16
char mqtt_server[40];
bool shouldSaveConfig = false;
void saveConfigCallback () { Serial.println("Should save config"); shouldSaveConfig = true; }
WiFiManager wifiManager;
WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40);
void setup() {
Serial.begin(115200);
Serial.println("\n Starting");
pinMode(TRIGGER_PIN, INPUT);
//clean FS, for testing
//SPIFFS.format();
if (SPIFFS.begin()) {
Serial.println("** Mounting file system **");
if (SPIFFS.exists("/config.json")) {
//file exists, reading and loading
Serial.println("** Reading config file **");
File configFile = SPIFFS.open("/config.json", "r");
if (configFile) {
size_t size = configFile.size();
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
configFile.readBytes(buf.get(), size);
DynamicJsonDocument doc(1024);
DeserializationError error = deserializeJson(doc, buf.get());
// Test if parsing succeeds.
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.c_str());
return;
}
strcpy(mqtt_server, doc["mqtt_server"]); //get the mqtt_server <== you need one of these for each param
} else {
Serial.println("** Failed to load json config **");
}
configFile.close();
Serial.println("** Closed file **");
}
}
else {
Serial.println("** Failed to mount FS **");
}
wifiManager.setSaveConfigCallback(saveConfigCallback);
wifiManager.addParameter(&custom_mqtt_server);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
resetbtn();
}
Serial.println("connected...yeey :)");
//read updated parameters
strcpy(mqtt_server, custom_mqtt_server.getValue());
//save the custom parameters to FS
if (shouldSaveConfig) {
Serial.println("saving config");
DynamicJsonDocument doc(1024);
doc["mqtt_server"] = mqtt_server;
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) {
Serial.println("failed to open config file for writing");
}
serializeJson(doc, Serial);
serializeJson(doc, configFile);
configFile.close();
//end save
}
}
void loop() {
resetbtn();
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
resetbtn();
}
Serial.println("Connected");
wifiManager.process();
saveParamsCallback();
delay(3000);
}
void resetbtn() { if ( digitalRead(TRIGGER_PIN) == HIGH ) { wifiManager.startConfigPortal("Horray"); Serial.println("connected...yeey :)"); } }
void saveParamsCallback () {
Serial.println("Get Params:");
Serial.print(custom_mqtt_server.getID());
Serial.print(" : ");
Serial.println(custom_mqtt_server.getValue());
}
for same purpose instead of using: serializeJson(doc, configFile);
i'm using this function and for me work pretty well
// for writing
bool writeFile(const char * path, const char * message, unsigned int len){
File file = SPIFFS.open(path, FILE_WRITE);
if(!file){
return false;
}
if(!file.write((const uint8_t *)message, len)){
return false;
}
return true;
}
for reading i'm using this function
// for reading
int readFile(const char * path, char ** text){
// retval int - number of characters in the file
// in case of empty file 0
// in case of directory or not found -1
File file = SPIFFS.open(path);
if(!file || file.isDirectory()){
return -1;
}
int file_lenght = file.size();
*text = (char*) malloc(file_lenght*sizeof(char));
for(int i = 0; i < file_lenght; i++){
(*text)[i] = file.read();
}
return file_lenght;
}
you can use this function in this way:
#define WIFI_credential_filename "/config.json"
char * wifi_credentials;
int file_len = readFile(WIFI_credential_filename, &wifi_credentials);
// at this point "wifi_credentials" is filled with the content of
"/config.json" file
this is my implementation, surely it can be improved but I have tested it and it works

7Digit Display counting bug

I am trying to fix the bug in my code - I have 7Digit display, which must count up from 0 to 99 when button is not pressed, or count down from 99 to 0 when button is pressed.
I have the issue with counting up, the issue happens, when the display must show numbers as 10,20,30 etc. While countin it up, after number 09 there is 00 instead of 10, after 19 there is 10 instead of 20 etc.
I am attching below a fragment of code responsible for counting up and down:
void Refresh_Display() {
AT91C_BASE_PIOB->PIO_CODR = A|B|C|D|E|F|G;
}
void set_Number(int number) {
AT91C_BASE_PIOB->PIO_SODR = LEFTDIGIT;
AT91C_BASE_PIOB->PIO_CODR = RIGHTDIGIT;
Refresh_Display();
Display_Number(number%10);
delay(5000);
AT91C_BASE_PIOB->PIO_SODR = RIGHTDIGIT;
AT91C_BASE_PIOB->PIO_CODR = LEFTDIGIT;
Refresh_Display();
Display_Number(number/10);
delay(5000);
}
void countdown(int i) {
while(1) {
if(i<=0) {
i = 99;
}
set_Number(i);
i--;
if(!BP1_Status) {
counter = i;
break;
}
}
}
void countup(int i) {
while(1) {
i++;
if(i>=99) {
i = 0;
}
set_Number(i);
if(BP1_Status) {
counter = i;
break;
}
}
}
int main(void){
Port_init();
Button_init();
while(1) {
for (volatile int i=0;i<100;i++) {
if(BP1_Status) {
countdown(counter);
} else if (!BP1_Status) {
countup(counter);
}
}
}
}
I have a solution for that problem:
In the ARM processor AT91SAM9263 there are registers PIO_CODR and PIO_SODR. The first one register is refreshing data, the second one Sets the data to be driven on the I/O line.
I have swapped the method of display the numbers on two 7Segment Displays. On the left, there are displayed, the decimal numbers are displayed as number/10 and the units as numbers%10to receive 0 digit on second display while showing 10 or 20 value.
void set_Number(int number) {
AT91C_BASE_PIOB->PIO_CODR = LEFTDIGIT;
AT91C_BASE_PIOB->PIO_SODR = RIGHTDIGIT;
Refresh_Display();
Display_Number(number/10);
delay(5000);
AT91C_BASE_PIOB->PIO_CODR = RIGHTDIGIT;
AT91C_BASE_PIOB->PIO_SODR = LEFTDIGIT;
Refresh_Display();
Display_Number(number%10);
delay(5000);
}

RPi 4 GPIO Interrupt on Rising and Falling trigger not working in C

Beginner here learning to code linux kernel modules.
I want to write a kernel module for my RPi 4 in C language.
I want to use interrupts to light on a LED when I push a button. As long as the button is pushed, the LED is on and when I release it, the LED is supposed to turn off.
I use the function request_irq() so that my function handling the interrupt is called on the rising edge and on the falling edge of my button by indicating "IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING". I formerly used the function gpio_to_irq(BUTTON_PIN).
request_irq(button_irq, button_ih, IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING, "button_irq", NULL);
The function is called when I push the button but not when I release it. It is coded as seen below :
static irqreturn_t button_ih(int irq, void *data)
{
int state;
state = gpio_get_value(BUTTON_PIN);
printk(KERN_INFO "Actual state of the button : %d", state);
//Debounce condition
if(jiffies - last_interrupt_time > msecs_to_jiffies(200))
{
if(state)
{
gpio_set_value(LED_PIN, 1);
}else
{
gpio_set_value(LED_PIN, 0);
}
}
last_interrupt_time = jiffies;
return IRQ_HANDLED;
}
I check whether the value of the button is 1 (pressed) or 0 (released) and want to turn on/off the LED accordingly.
When I try different GPIOs, sometimes, the value of my button is 1 even though I haven't pushed it yet(by printing a message from the init function) and sometimes it's 0. So I don't understand if I'm doing something wrong. I don't think the GPIOs are already used cause I can request them with the function gpio_request_one().
So when the button already has the value 1, the LED turn on but won't switch off when I release the button.
And when the value is already 0, the button value doesn't change to become 1 when I enter the interrupt handler function (and the LED obviously doesn't turn on).
Could you tell me what's wrong with it please?
Form simple C program, not kernel module
This minimal to see how I'm doing.
main.h
typedef struct s_Data {
int exitFlag;
struct {int value; int bcmPin;} In01; //<--- Stock actual GPIO Value
struct {int value; int bcmPin;} In02;
....
struct {int value; int bcmPin;} Out01;
struct {int value; int bcmPin;} Out02;
....
} t_Data;
#define NO_Click 0
#define SimpleClick 1
#define LongClick 2
#define MultiClick 3
typedef struct s_Button {
pthread_t button_thread;
int *exitFlag;
int * input; //Button
int * output;
int old_state;
int new_state;
struct timeval t0;
struct timeval t1;
struct timeval pressedTime;
struct timeval releasedTime;
int clickType;
//float debounce = 0.020; // ms debounce period to prevent flickering when pressing or releasing the button
// debounce not necessary while thread have time to take a coffee
float DCgap; // max ms between clicks for a double click event
float holdTime; // ms hold period: how long to wait for press+hold event
} t_Button;
main.c
#include "main.h"
#include <wiringPi.h>
#include <pthread.h>
// initial state
static t_Data data = {
.exitFlag = 0,
.In01.value = 0, .In01.bcmPin = 4,
.In02.value = 0, .In02.bcmPin = 17,
.Out01.value = 0, .Out01.bcmPin = 4,
.Out02.value = 0, .Out02.bcmPin = 17,
}
static _Data data_prev;
static void *inputRead_threadFn(void *p_Data) {
pinMode(Data.In01.bcmPin, INPUT);
pullUpDnControl(Data.In01.bcmPin, PUD_UP);
pinMode(Data.In02.bcmPin, INPUT);
pullUpDnControl(Data.In02.bcmPin, PUD_UP);
while (!Data.exitFlag) {
Data.In01.value = !digitalRead(Data.In01.bcmPin);
Data.In02.value = !digitalRead(Data.In02.bcmPin);
if (Data.In01.value != Data_old.In01.value) {
Data_old.In01.value = Data.In01.value;
}
if (Data.In02.value != Data_old.In02.value) {
Data_old.In02.value = Data.In02.value;
}
usleep(50)
}
}
static void *outputWrite_threadFn(void *p_Data) {
pinMode(Data.In01.bcmPin, OUTPUT);
pinMode(Data.In02.bcmPin, OUTPUT);
while (!Data.exitFlag) {
digitalWrite(Data.Out01.bcmPin, !Data.Out01.value);
digitalWrite(Data.Out02.bcmPin, !Data.Out02.value);
}
usleep(50)
}
static void *button_threadFn(void *p_Data) {
t_Button *button = (t_Button *)p_data;
LOG("Button[%s] thread initialized\r\n", button->name);
button->old_state = 0;
button->new_state = 0;
button->clickType = NO_Click;
int clickCount = 0;
while(*(button->exitFlag) == 0) {
button->new_state = *(button->input) || *(button->web_input); //*((int *)
if( button->old_state == 0 && button->new_state == 1 ) {
//printf("front montant\r\n"); fflush(stdout);
// *****************************
// traitement sur front montant
// rising edge
// *****************************
button->old_state = 1;
gettimeofday(&button->pressedTime, 0);
//Button pressed
} else if( (button->old_state == 1) && (button->new_state == 0) ) {
//printf("front descendant\r\n"); fflush(stdout);
// *****************************
// traitement sur front descendant
// falling edge
// *****************************
button->old_state = 0;
gettimeofday(&button->releasedTime, 0);
if (my_timedifference_msec(button->releasedTime, button->pressedTime ) < button->DCgap) {
clickCount++;
button->clickType = MultiClick;
}
//Button released
} else if( (button->old_state == 0) && (button->new_state == 0) ) {
// printf("front bas\r\n"); fflush(stdout);
// *****************************
// pas de changement d'état : front bas
// no state change : edge down
// *****************************
gettimeofday(&button->t0, 0);
*(button->output) = 0; //<--- here in your case
//Attendre DC_Gap pour connaitre le nombre de click
// Wait for DC_Gap to know click count
if (my_timedifference_msec(button->t0, button->releasedTime) > button->DCgap) {
if (clickCount == 1) {
LOG("SimpleClick");
//Simple Click
} else if ( clickCount > 1 ) {
//Multiclicks
}
button->clickType = NO_Click;
clickCount = 0;
}
} else if( (button->old_state == 1) && (button->new_state == 1) ) {
// printf("front haut\r\n"); fflush(stdout);
// *****************************
// pas de changement d'état : front haut
// no state change : edge up
// *****************************
gettimeofday(&button->t1, 0);
*(button->output) = 1; //<--- here in your case
//long click
if (my_timedifference_msec(button->t1, button->pressedTime) >= button->holdTime) {
LOG("LongClick");
button->clickType = LongClick;
//do what you want while not released
usleep(30*1000);
}
}
usleep(100);
}
printf("Light Loop::exiting...\r\n"); fflush(stdout);
}
int main(int argc, char** argv) {
wiringPiSetup();
wiringPiSetupGpio();
data_prev = data;
//start input thread
//start output thread
int DCGap = 250; //ms
int HoldTime = 600;
t_Button Buttons[] = {
{ //WC
.exitFlag = &Data.exitFlag,
.DCgap = DCGap,
.holdTime = HoldTime,
.input = &Data.In01.value,
.output = &Data.Out01.value,
},
{ //chambre
.exitFlag = &Data.exitFlag,
.DCgap = DCGap,
.holdTime = HoldTime,
.input = &Data.In02.value,
.output= &Data.Out02.value,
}
}
//start buttons threads
for (i = 0; i < (sizeof(Buttons) / sizeof(t_Button)) ; i++) {
ret = pthread_create (&Buttons[i].button_threadFn, NULL, fn_Button, &Buttons[i]);
if (ret) {
fprintf (stderr, "%s", strerror (ret));
}
}
//threads join
return (EXIT_SUCCESS);
}
Ok so thanks for all the comments/answers.
It was indeed because I wasn't using any pull-up or pull-down resistor properly.
So I changed my circuit as following:
Circuit

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