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.
Related
I need to ring the buzzer within the range of 1 meter only, my esp8266 is connected to a buzzer but the buzzer will ring on and off within the range of 1 meter using two esp8266, or sometimes it does not ring at all. The project is social distancing, what else should I do? Here is the code I am using:
#include <ESP8266WiFi.h>
const char* APssid = "Social Distancing"; //acess point of the device
const char* APpassword = "qwertyuiop";
const int RSSI_MAX = -37;//maximum strength of signal in dBm
const int RSSI_MIN =-100;//minimum strength of signal in dBm
void setup()
{
WiFi.mode(WIFI_OFF);
WiFi.disconnect();
delay(50); //this part turns off the wifi and resets it if it was already on
Serial.begin(115200);
pinMode(14,OUTPUT);
Serial.println();
WiFi.mode(WIFI_AP_STA); //configuring the board in hybrid mode
Serial.print("Configuring access point...");
WiFi.softAP(APssid, APpassword);
Serial.println(WiFi.softAPIP());
}
void loop()
{
Serial.println("Wifi is scanning");
int n = WiFi.scanNetworks();
Serial.println("Wifi scan ended");
if (n == 0)
{
Serial.println("no networks found");
}
else
{
Serial.print(n);
Serial.println(" networks found");
for (int i = 0; i < n; ++i)
{
//Print SSID and RSSI for each network found
Serial.print(i + 1);
Serial.print(") ");
Serial.print(WiFi.SSID(i));//SSID
Serial.print(WiFi.RSSI(i));//Signal strength in dBm
Serial.print("dBm (");
if(WiFi.SSID(i) == "Social Distancing")
{
if(WiFi.RSSI(i) > -37)//THIS -37 (RSSI) is the threshold value, this value is set
according to the distance of 1m
{
digitalWrite(14,HIGH);//(Generic esp8266 : (14,HIGH) , NodeMCU : (D5,HIGH) )
Serial.println("Social Distancing");
break;
}
}
else
{
digitalWrite(14,LOW);
}
}
delay(50);
}
Serial.println("");
delay(50);
WiFi.scanDelete();
}
Hi Lisa I have modified your code and I have added a 64x48 OLED display connected to the I2C connections, to visualize the results and it works beautifully. Moreover I have used the built in led (see: LED_BUILTIN) instead of the buzzer.
You have had a great idea. Now it works great and you can interrogate any Access point.
Please find attached the code:
//OLED
#include <Arduino.h>
#include <U8g2lib.h>
#include <U8x8lib.h> //this one in use
#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif
U8X8_SSD1306_64X48_ER_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE); // EastRising 0.66" OLED breakout board, Uno: A4=SDA, A5=SCL, 5V powered
// End of constructor list
#define U8LOG_WIDTH 16
#define U8LOG_HEIGHT 8
uint8_t u8log_buffer[U8LOG_WIDTH*U8LOG_HEIGHT];
U8X8LOG u8x8log;
//OLED end
#include <ESP8266WiFi.h>
const char* APssid = "My_SSID"; //acess point of the device
const char* APpassword = "My_Password";
//const char* myconstcharstarstring = "------------------------------";
const int RSSI_MAX = -37;//maximum strength of signal in dBm
const int RSSI_MIN =-100;//minimum strength of signal in dBm
void setup()
{
//OLED
u8x8.begin();
u8x8.setFont(u8x8_font_chroma48medium8_r);
u8x8log.begin(u8x8, U8LOG_WIDTH, U8LOG_HEIGHT, u8log_buffer);
u8x8log.setRedrawMode(1); // 0: Update screen with newline, 1: Update screen for every char
//OLED end
WiFi.mode(WIFI_OFF);
WiFi.disconnect();
delay(50); //this part turns off the wifi and resets it if it was already on
Serial.begin(115200);
pinMode(LED_BUILTIN,OUTPUT);
Serial.println();
WiFi.mode(WIFI_AP_STA); //configuring the board in hybrid mode
Serial.print("Configuring access point...");
WiFi.softAP(APssid, APpassword);
Serial.println(WiFi.softAPIP());
}
void loop()
{
digitalWrite(LED_BUILTIN,LOW);
Serial.println("Wifi is scanning");
int n = WiFi.scanNetworks();
Serial.println("Wifi scan ended");
if (n == 0)
{
Serial.println("no networks found");
}
else
{
Serial.print(n);
Serial.println(" networks found");
for (int i = 0; i < n; ++i)
{
//Print SSID and RSSI for each network found
Serial.print(i + 1);
Serial.print(") ");
Serial.print(WiFi.SSID(i));//SSID
Serial.print(WiFi.RSSI(i));//Signal strength in dBm
Serial.print("dBm (");
if(WiFi.RSSI(i) > -37)//THIS -37 (RSSI) is the threshold value, this value is set according to the distance of 1m
{
digitalWrite(LED_BUILTIN,HIGH);//(Generic esp8266 : (14,HIGH) , NodeMCU : (D5,HIGH) )
Serial.println("Social Distancing");
delay(500);
}
//OLED
u8x8log.print(WiFi.SSID(i));
u8x8log.print("\n");
u8x8log.print(WiFi.RSSI(i));
u8x8log.print("\n");
u8x8log.print("-------------");
u8x8log.print("\n");
delay(2000);
}
Serial.println("");
delay(50);
WiFi.scanDelete();
}
}
Hope this answers All the best
Hi Lisa please add digitalWrite(14,HIGH); at the beginning of the loop, it will work:
void loop()
{
digitalWrite(14,HIGH);
/... rest of your code...
I don't know how you have wired your buzzer, try forcing your ouput pin HIGH or LOW depending on your circuit.
Hope this helps All the best
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();
}
}
}
I'm unable to break out of an if statement after a button has been depressed. The button activates a relay and the depression turns the relay off.
Here is my full code: I'm new to C so all comments and suggestions are much appreciated.
#include "mcc_generated_files/mcc.h"
#define FCY 8000000UL
#include <libpic30.h>
//#define baudrate 19200
int main(void)
{
// Initialise the device
SYSTEM_Initialize();
while(1)
{
LED4_SetLow(); // Turn on 3v3 LED
LED12v_SetHigh();
LED3_SetHigh();
LED1_SetHigh();
int button;
button = UART5_Read();
if (button == 0x08)
{
RLY1_SetHigh();
RLY3_SetHigh();
if (button == 0x00)
goto finished;
}
finished:
RLY1_SetLow();
RLY3_SetLow();
}
return (0);
}
I have now edited the code as follows. The relays are able to be set high but the condition 0x00 is never reached. Can someone please explain?
#include "mcc_generated_files/mcc.h"
#define FCY 8000000UL
#include <libpic30.h>
//#define baudrate 19200
int main(void)
{
// Initialise the device
SYSTEM_Initialize();
while(1)
{
LED4_SetLow(); // Turn on 3v3 LED
LED12v_SetHigh();
LED3_SetHigh();
LED1_SetHigh();
int button;
int release;
button = UART5_Read();
release = UART5_Read();
if (button == 0x08)
{
RLY1_SetHigh();
RLY3_SetHigh();
}
if (release == 0x00)
{
RLY1_SetLow();
RLY3_SetLow();
}
__delay_ms(1000);
}
return (0);
}
I haven't used this MCU nor its libs, but I believe correct code should look something along the lines of this:
#include "mcc_generated_files/mcc.h"
#include <libpic30.h>
#include <stdint.h>
#define BUTTON_CODE 0x8u // use named constants instead of magic numbers
void main (void)
{
// Initialise the device
SYSTEM_Initialize();
for(;;)
{
uint8_t data;
LED4_SetLow(); // Turn on 3v3 LED
LED12v_SetHigh();
LED3_SetHigh();
LED1_SetHigh();
if(UART5_Data_Ready())
{
data = UART5_Read();
if(data == BUTTON_CODE)
{
RLY1_SetHigh();
RLY3_SetHigh();
}
else
{
RLY1_SetLow();
RLY3_SetLow();
}
}
}
}
/*This code takes in inputs from IR sensors connected on PA0 and PA1
and glows LEDs connected on PB0 and PB1*/
#include <avr/io.h>
int main()
{
DDRA=0x00; // PORTA (PA0 and PA1) will act as input
DDRB=0x03; //The last two pins PBO and PB1 will act as output.
int x=0x03 & PINA; //Initially when PINA=0, x=0
if (x==0x00)
{
PORTB=0x00;
}
else if (x==0x01)
// If input is given to PA0 then PINA=0x01 and x=0x01
{
PORTB=0x01;
}
else if (x==0x02)
// If input is given to PA1 then PINA=0x02 and x=0x02
{
PORTB=0x02;
}
else if(x==0x03)
// If input is given to PA0 and PA1 then PINA=0x03 and x=0x03
{
PORTB=0x03;
}
return 0;
}
A solution to have a program that runs continuously is that below. This solution contains some logic adjustments to your code. The logic adjustments allow the code to don't modify all the bits of the port B, in this way the code modifies only the bits 0 and 1 of the port. That allows to use the other bits for other purposes.
#include <avr/io.h>
void main()
{
DDRA=0x00; // PORTA (PA0 and PA1) will act as input
DDRB=0x03; //The last two pins PBO and PB1 will act as output.
int x;
PORTB=0;
PORTA=0;
for( ;; ) {
x=0x03 & PINA; //Initially when PINA=0, x=0
if (x==0x00)
{
PORTB&=(~3);
}
else if (x==0x01)
// If input is given to PA0 then PINA=0x01 and x=0x01
{
PORTB&=(~2);
PORTB|=0x01;
}
else if (x==0x02)
// If input is given to PA1 then PINA=0x02 and x=0x02
{
PORTB&=(~1);
PORTB|=0x02;
}
else`enter code here` if(x==0x03)
// If input is given to PA0 and PA1 then PINA=0x03 and x=0x03
{
PORTB|=0x03;
}
// Here you may insert a delay
//delay(50);
}
}
I think a good solution might be the following code:
#include <avr/io.h>
void main()
{
DDRA=0x00; // PORTA (PA0 and PA1) will act as input
DDRB=0x03; //The last two pins PBO and PB1 will act as output.
PORTB=0;
PORTA=0;
for( ;; ) {
PORTB &=(~3);
PORTB |= (PORTA & 3);
// Here you may insert a delay
// delay(50);
}
}
I`m trying to blink led with PWM on Arduino, and I dont know whats wrong. But my LED is not fadeing. What is wrong? I think that I have bad registers settings, but Im not sure. Led is connected on arduino pin 11. Thank you.
#include <avr/io.h>
#include <util/delay.h>
const int delay=1000;
void initialize_PWM()
{
TCCR0A|=(1<<WGM00)|(1<<WGM01)|(1<<COM0A1);
TCCR0B=1;
DDRB|=(1<<PB3);
}
void set_pwm(uint8_t data)
{
OCR0A=data;
}
int main (void)
{
initialize_PWM();
uint8_t brightness=200;
while(1)
{
for(brightness=0;brightness<255;brightness++)
{
set_pwm(brightness);
_delay_ms(1);
}
for(brightness=255;brightness>0;brightness--)
{
set_pwm(brightness);
_delay_ms(1);
}
}
return 0;
}
Have you looked at the 'Fade' example program?
/*
Fade
This example shows how to fade an LED on pin 9
using the analogWrite() function.
This example code is in the public domain.
*/
int led = 9; // the pin that the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by
// the setup routine runs once when you press reset:
void setup() {
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
// set the brightness of pin 9:
analogWrite(led, brightness);
// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;
// reverse the direction of the fading at the ends of the fade:
if (brightness == 0 || brightness == 255) {
fadeAmount = -fadeAmount ;
}
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
See http://arduino.cc/en/Tutorial/Fade
Your code seems correct, but you are using timer0, that can generate pwm on Arduino UNO's pin 5 and 6, as shown in the datasheet. So you should set the ddrd bit 6 with a
DDRD |= (1 << PD6)
, that is pin 6 on Arduino, not pin 11. If you want pwm on pin 11 you should use timer2 instead.