Take input in an infinte loop in c - c

I am writing a C program to blink LED for Raspberry Pi. Its like (i) Blink LED (2) Stop blinking it.
Now while the LED is blinking, if I press 2 it should stop blinking. How to do it ?
If I include scanf inside the code will stop blinking.
while(1)
{
printf("Enter a command \n 1.Blink Led\n 2. Stop blinking\n");
scanf("%d",&choice);
if(choice==1)
for (;;)
{
digitalWrite (LED, HIGH) ; // On
delay (500) ; // mS
digitalWrite (LED, LOW) ; // Off
delay (500) ;
// If i press 2 the led should stop blinking
}
else if(choice==2){
digitalWrite (LED, LOW) ;
}

if you don't want to interrupt the Blinking you should try to run the blinking in a parallel process using pthread_t.
i really want to give you the code but i'm not on my PC at the moment.

Use poll:
#include <stdio.h>
#include <unistd.h>
#include <poll.h>
int main()
{
struct pollfd mypoll = { STDIN_FILENO, POLLIN|POLLPRI };
unsigned char c, blink=1, on =1, q=1;
while(q) {
if( poll(&mypoll, 1, 500) ) {
c=getchar();
switch(c) {
case '1':
blink = 1;
break;
case '2':
blink =0;
break;
case 'q':
q= 0;
break;
}
}
else{
if (blink) {
if (on)
on =0;
else
on =1;
}
printf("%u\n",on);
}
}
return 0;
}
replace the on parameter with the led functions.

Related

SPI Communication between ATMEGA 324PB and Arduino Nano

Here I'm trying to Send the SPI command from the master (Arduino Nano) to the slave(ATMEGA324PB).
First Master receives a command from the serial monitor. When the serial message receives completely, the Master passes the message to the Slave. Whenever the slave has a message to send, it will interrupt the Arduino nano using pin 3. However, in the first round slave send messages to master, and master can read it successfully. But in the second round It couldn't happen. I was unable to find the issue. I will attach the codes below.
User message is like in this manner XF01600#.
Send X (or Y)
Send F (or B)
Send 01600
Send #
This is my Master Code :
` #include <SPI.h>`
char Direction;
char Axis;
char TxCommand;
char TxEnd;
bool stringComplete = false; // Is receive complete ?
bool TxComplete=false;
int k=0;
int j=0;
String StepCount;
SPISettings setting(200000,MSBFIRST,SPI_MODE0);
void setup() {
Serial.begin(9600);
pinMode(10,OUTPUT);
pinMode(9,OUTPUT);
pinMode(2,OUTPUT);
attachInterrupt(digitalPinToInterrupt(3),SlaveReceive,RISING);
SPI.begin();
}
void SlaveReceive(){
SPI.begin();
SPI.beginTransaction(setting);
digitalWrite(10,LOW);
TxCommand=SPI.transfer(0xFF);//dummy
TxEnd=SPI.transfer(0xFF);//dummy
digitalWrite(10,HIGH);
SPI.endTransaction();
Serial.print("Received Command-");
Serial.println(TxCommand );
Serial.print("Received End-");
Serial.println(TxEnd);
if(TxEnd=='~'){
TxComplete=true;
}
}
void SPI_Transfer(){
SPI.transfer(Direction);//transfer direction
delay(5);
SPI.transfer(StepCount.length());//transfer incoming step length
delay(5);
for(int i=0;i<StepCount.length();i++){//transfer step count;
SPI.transfer(StepCount[i]);
Serial.println(StepCount[i]);
delay(5);
}
SPI.transfer('#');
delay(5);
}
void loop() {
if (stringComplete) {
if(Direction=='F'){
digitalWrite(2,HIGH);
}
else if(Direction=='B'){
digitalWrite(2,LOW);
}
Serial.print("Direction-");
Serial.println(Direction);
Serial.println(StepCount);
Serial.println(StepCount.length());
SPI.beginTransaction(setting);
if(Axis=='X'){ // Chip Select line for X axis driver is pin 10;
digitalWrite(10,LOW);
SPI_Transfer();
digitalWrite(10,HIGH);
}
else if(Axis=='Y'){ /// Chip select line for Y axis driver is pin 9;
digitalWrite(9,LOW);
SPI_Transfer();
digitalWrite(9,HIGH);
}
SPI.endTransaction();
stringComplete = false;
k=0;
}
if(TxComplete){
if(TxCommand=='S'){
digitalWrite(2,LOW);
TxComplete=false;
}
}
}
void serialEvent() {
while (Serial.available()>0) {
if(k==0){
Axis = Serial.read();
k++;
}
else if(k==1){
Direction=Serial.read();
k++;
}
else if(Serial.read()!='#'){
//StepCount[k-1]=Serial.readString();
StepCount=Serial.parseInt();
k++;
}
else{
stringComplete = true;
}
}
}
Slave Main Command :
while(1){
if(SPI_RECEIVE_COMPLETE){
SPI_RECEIVE_COMPLETE=false;
PORTA |=(1<<4);
Decode_SPI_Command();
switch (SPI_Command)
{
case 'F':
_Run_Motor(SPI_Data, true, 1, 0.3);//10 CYCLE
SlaveSendData(0x53);//S
break;
case 'B':
_Run_Motor(SPI_Data, false, 1, 0.3);
SlaveSendData(0x53);//S
break;
}
for(uint8_t i=0;i<15;i++){
SPI_Received_Data[i]=0;
}
SPI_Data=0;
SPI_BYTES_Transfer=0;
}
PORTA &=~(1<<4);
}
The Slave data send function:
void SlaveSendData(uint8_t SlaveCommand){
SPI_BYTES_Transfer=0;
SPI_Data_TX=true;
SPDR1=SlaveCommand;
SPI_Transmit_Data[0]=0x7E;//~
PORTA |=(1<<3);
_delay_ms(10);
PORTA &=~(1<<3);
}
Slave SPI interrupt function:
ISR(SPI1_STC_vect){
if(SPI_Data_TX){//slave is transmitting data
SPDR1 = SPI_Transmit_Data[SPI_BYTES_Transfer];
SPI_BYTES_Transfer++;
if(SPI_Received_Data[SPI_BYTES_Transfer-1]=='~'){
SPI_Data_TX=false;
//SPDR1=0x00;
SPI_BYTES_Transfer=0;
}
}
else{
SPI_Received_Data[SPI_BYTES_Transfer] = SPDR1;
SPI_BYTES_Transfer++;
if(SPI_Received_Data[SPI_BYTES_Transfer-1]=='#'){
SPI_RECEIVE_COMPLETE=true;
SPDR1=0x00;
}
}
}
Here I have found that in the else part SPI_RECEIVE_COMPLETE=true; never occurs on the second try. But I couldn't find where the issue is..?
serial monitor
Arduino Serial Monitor
Could you please take a look, Thank you.

Embedded C (FreeRTOS)

Trying to create a reaction timer. Timer rand counts down from 10. LED is red and turns green when the user has pressed the switch. The user has to press either sw2 or sw3 when prompted has a 5 second gap to press switch. Once switch is pressed, the time is recorded and printed to putty. Game then resets and user can play again.
I'm current stuck trying to implement the LED and rand timer, could anyone help:
#include "freeRTOS.h"
#include "task.h"
#include "semphr.h"
#include "queue.h"
#include "timers.h"
#include "event_groups.h"
#include <stdio.h>
#include "board.h"
#include "peripherals.h"
#include "pin_mux.h"
#include "clock_config.h"
#include "MK64F12.h"
#include "fsl_debug_console.h"
#include "fsl_UART.h"
#include "fsl_device_registers.h"
/* TODO: insert other definitions and declarations here. */
QueueHandle_t switchQueue = NULL;
TaskHandle_t displayHandle = NULL, UARTHandle =NULL, LED_TaskHandle = NULL;
static void displayTask(void * pvParameters);
static void LED_Task(void *pvParameters);
static EventGroupHandle_t SW_Group = NULL;
#define SW2_bit 1<<0
#define SW3_bit 1<<1
/*
* #brief Application entry point.
*/
void BOARD_SW2_IRQ_HANDLER(){
static int8_t count = 0;
static uint32_t buffer[5];
BaseType_t xHigherPriorityTaskWoken;
PORT_ClearPinsInterruptFlags(BOARD_SW2_PORT, 1<<BOARD_SW2_GPIO_PIN);
buffer[count] = xTaskGetTickCountFromISR()*(1000/configTICK_RATE_HZ);
printf("\n\rSW2 pressed at %d", buffer[count]);
/* if(GPIO_PinRead(BOARD_INITPINS_SW2_GPIO,BOARD_INITPINS_SW2_PIN)== 0)
{
PRINTF("Switch pressed!.\r\n");
xEventGroupSetBits(SW_Group, SW2_bit);
while(GPIO_PinRead(BOARD_INITPINS_SW2_GPIO,BOARD_INITPINS_SW2_PIN) == 0){}
//vTaskSuspend(NULL);
if(++count==5){
count=0;
xHigherPriorityTaskWoken = pdFALSE;
//send copy of buffer to queue
xQueueSendFromISR(switchQueue, buffer, &xHigherPriorityTaskWoken);
portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
}
}*/
vTaskDelay(pdMS_TO_TICKS(100));
}
int main(void) {
/* Init board hardware. */
BOARD_InitBootPins();
BOARD_InitBootClocks();
BOARD_InitBootPeripherals();
/* Init FSL debug console. */
BOARD_InitDebugConsole();
BOARD_InitLEDsPins();
//configure sw2 interrupt
NVIC_SetPriority(BOARD_SW2_IRQ, 10);
NVIC_ClearPendingIRQ(BOARD_SW2_IRQ);
NVIC_EnableIRQ(BOARD_SW2_IRQ);
SW_Group = xEventGroupCreate();
switchQueue = xQueueCreate(5,20); //5 item queue of 20 bytes per item
if(xTaskCreate(displayTask, "Time Display", 100, NULL, 3, &displayHandle)== pdFALSE)
{
printf("UART task not created\n\r");
while(1)
;
}
if (xTaskCreate(LED_Task, "LED_Task", configMINIMAL_STACK_SIZE + 10, NULL, 4, &LED_TaskHandle) != pdPASS)
{
PRINTF("LED_Task creation failed!.\r\n");
while (1)
;
}
vTaskStartScheduler();
volatile static int i = 0;
/* Enter an infinite loop, just incrementing a counter. */
while(1){
i++;
}
return 0 ;
}
static void displayTask(void * pvParameters){
uint32_t rxBuffer[5];
printf("Starting display task\n\r");
while(1){
if(xQueueReceive(switchQueue, &rxBuffer, portMAX_DELAY) == pdTRUE){
//print data
printf("\n\n\rData Received from Queue:");
int x;
for(x=0;x<5;x++){
printf("\n\rData %d: %d",x,rxBuffer[x]);
}
vTaskDelay(pdMS_TO_TICKS(100));
}
}
}
void LED_Task(void *pvParameters)
{
EventBits_t event_bits;
for (;;) //no conditions in the for loop, will run forever
{
event_bits = xEventGroupWaitBits(SW_Group, SW2_bit | SW3_bit, pdTRUE, pdFALSE, portMAX_DELAY);
if(event_bits & SW2_bit){
PRINTF("Event bit set, RED LED Toggled!.\r\n");
LED_RED_TOGGLE();
}
else if(event_bits & SW3_bit){
PRINTF("Event bit set, GREEN LED Toggled!.\r\n");
LED_GREEN_TOGGLE();
}
}
}

How can I access second if statment after choosing first if statment without restarting the serial?

I wrote a program to send IR Signal to my audio player, SendChannelUpCode and SendChannelUpCodeONE is responsible for sending two types of IR signals one for playing a CD and the other for AUX mode, if i open the serial and if i type 1 CD mode it will run but i cant type "2" again and send another signal i must turn off then on the serial then press 2 to run, any suggestions of how to not restart the serial everytime to change between the modes?
I have tried using return on the SendChannelUpCode function and tried putting exit(1) after i call the function but still having the same problem, and i cant use break functions because its in an IF statement error
void setup(){
pinMode(IRledPin, OUTPUT);
Serial.begin(9600);
while (!Serial);
Serial.println("Input 1 to Turn CD on and 2 to turn AUX mode");
}
void loop() {
if (Serial.available())
{
int state = Serial.parseInt();
if (state == 1)
{
Serial.println("Command completed, CD MODE ON");
delay(100);
SendChannelUpCode();
}
if (state == 2)
{
Serial.println("Command completed, AUX MODE ON");
delay(100);
SendChannelUpCodeONE();
}
}
}
void pulseIR(long microsecs) {
cli();
while (microsecs > 0) {
digitalWrite(IRledPin, HIGH);
delayMicroseconds(10);
digitalWrite(IRledPin, LOW);
delayMicroseconds(10);
microsecs -= 26;
}
}
void SendChannelUpCode() {
delayMicroseconds(28136 ); //Time off (LEFT column)
pulseIR(9280 );
delayMicroseconds(4600 );
pulseIR(600 );
}
void SendChannelUpCodeONE() {
delayMicroseconds(28136 ); //Time off (LEFT column)
pulseIR(9280 );
delayMicroseconds(4600 );
pulseIR(600 );
}

Checking file exist in raspberry pi 2 using C language

I am new to C language and learning it by experimenting.
My challenge: I am trying to verify if a file "Command.txt" exist in a folder in raspberry pi and then I have to read the content of the file.
My Code:
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <wiringPi.h>
// Pin number declarations. We're using the Broadcom chip pin numbers.
const int pwmPin = 18; // PWM LED - Broadcom pin 18, P1 pin 12
const int ledPin = 23; // Regular LED - Broadcom pin 23, P1 pin 16
const int butPin = 17; // Active-low button - Broadcom pin 17, P1 pin 11
const int pwmValue = 75; // Use this to set an LED brightness
int file_exist(char *filename)
{
struct stat buffer;
return (stat(filename, &buffer) == 0);
}
int main(void)
{
// Setup stuff:
wiringPiSetupGpio(); // Initialize wiringPi -- using Broadcom pin numbers
pinMode(pwmPin, PWM_OUTPUT); // Set PWM LED as PWM output
pinMode(ledPin, OUTPUT); // Set regular LED as output
pinMode(butPin, INPUT); // Set button as INPUT
pullUpDnControl(butPin, PUD_UP); // Enable pull-up resistor on button
printf("Blinker is running! Press CTRL+C to quit.\n");
while(1)
{
FILE *command_file;
char command[255];
while(file_exist("/home/pi/FTP/command.txt"))
{
command_file = fopen("/home/pi/FTP/command.txt", "r");
fgets(command, 255, (FILE*)command_file);
printf("1: %s\n", command );
if(command == "First Light ON")
{
digitalWrite(ledPin, HIGH); //Change the raspberryPi pin state to 1
}
else if(command == "First Light OFF")
{
digitalWrite(ledPin, LOW); //Change the raspberryPi pin state to 0
}
else
{
printf("Command is not yet defined");
}
fclose(command_file);
}
while(!(file_exist("/home/pi/FTP/command.txt")))
{
printf("File does not exist\n");
delay(1000); // Wait 1s again
}
}
return 0;
}
When I run this code using the gcc command in my raspberry pi, The program is executed but I only see "File does not exist" message even if the file exist in the given folder.
Please help me with the logic on this program.

Could not call the sub-routine correctly Microcontroller PIC18F

I have a project to program a microcontroller PIC18F, I have to connect a switching circuit to the microcontroller board, this switching circuit has an electric lock and a buzzer to be connected to it.
The lock is initially powered. It is supposed that when I send '1', the buzzer will be powered with a square wave and the lock will be powered off. When it receives '0', the buzzer will be switched off without powering the lock again. When it receives '2' the lock should be powered but if the buzzer was unpowered before, it should not be powered again.
My confusion is in the last part. When I send '2' via the hyperterminal, and I sent '0' before it, the buzzer is powered again.
Here is the code,
void buzzertest();
char uart_rd;
int buzzer;
void main() {
TRISB=0X00;
PORTB=0x00;
RB5_bit = 0xFF; //lock open
UART1_Init(9600); // Initialize UART module at 9600 bps
while (1) { // Endless loop
if (UART1_Data_Ready()) // If data is received,
{
buzzer=1;
uart_rd = UART1_Read(); // read the received data,
if(uart_rd =='1') {
RB5_bit = 0x00; //lock closed
buzzertest();
}
if(uart_rd =='0' ){ //disable buzzer
RB1_bit = 0x00; //buzzer
buzzer=0;
}//end if
buzzer=0;
if(uart_rd =='2'){ //disable lock
RB5_bit=0xFF;
if(buzzer!=1){
buzzertest();
}
}//end if
} //end outer if
} //end while
}//end main
void buzzertest(){
while(1){
RB1_bit = 0xFF; //buzzer
Delay_ms(1000);
RB1_bit = 0x00; //buzzer
Delay_ms(1000);
if (UART1_Data_Ready())
break;
}//end while loop
}
Can please anyone help me solving this?
You're setting buzzer to 0 outside the if(uart_rd='0') block. So when you come to the if(uart_rd='2') block, buzzer is always 0 and so the if(buzzer!=1) block is always called.
Have you tried stepping through this with a debugger? It would show up this kind of thing easily. You could also change those if blocks either to a switch statement or a series of if / else if statements to avoid these sorts of issues.
here is the running code:
void buzzertest();
char uart_rd;
int buzzer;
void main() {
TRISB=0X00;
PORTB=0x00;
RB5_bit = 0xFF; //lock open
UART1_Init(9600); // Initialize UART module at 9600 bps
while (1) { // Endless loop
if (UART1_Data_Ready()) // If data is received,
{
uart_rd = UART1_Read(); // read the received data,
if(uart_rd =='1') {
RB5_bit = 0x00; //lock closed
buzzertest();
buzzer=1 ;
}
else if(uart_rd =='0' ){ //disable buzzer
RB1_bit = 0x00; //buzzer
buzzer=0;
}//end else if
else if(uart_rd =='2'){ //disable lock
RB5_bit=0xFF;
if(buzzer==1){
buzzertest();
}
}//end else if
} //end outer if
} //end while
}//end main
void buzzertest(){
while(1){
RB1_bit = 0xFF; //buzzer
Delay_ms(1000);
RB1_bit = 0x00; //buzzer
Delay_ms(1000);
if (UART1_Data_Ready())
break;
}//end while loop
}

Resources