Monday, July 29, 2019

infinite times execution using functions


#include <stdio.h>

void proc_task1();
void proc_task2();
void proc_task3();


int main()
{
    printf("\r\nit is inside main\r\n\n");
    proc_task1();
   

    return 0;
}

//proc_task1
void proc_task1()
{
    printf("\r\nit is inside proc_task1\r\n\n");
    proc_task2();
}

//proc_task2
void proc_task2()
{
    printf("\r\nit is inside proc_task2\r\n\n");
    proc_task3();
   
}

//proc_task3
void proc_task3()
{
    printf("\r\nit is inside proc_task3\r\n\n");
    proc_task1();
   
}





read the data from UART in QUECTEL MC60

/*****************************************************************************
*  Copyright Statement:
*  --------------------
*  This software is protected by Copyright and the information contained
*  herein is confidential. The software may not be copied and the information
*  contained herein may not be used or disclosed except with the written
*  permission of Quectel Co., Ltd. 2013
*
*****************************************************************************/
/*****************************************************************************
 *
 * Filename:
 * ---------
 *   example_gpio.c
 *
 * Project:
 * --------
 *   OpenCPU
 *
 * Description:
 * ------------
 *   This example demonstrates how to program a GPIO pin in OpenCPU.
 *   This example choose PINNAME_STATUS pin as GPIO.
 *
 *   All debug information will be output through DEBUG port.
 *
 *   The "Enum_PinName" enumeration defines all the GPIO pins.
 *
 * Usage:
 * ------
 *   Compile & Run:
 *
 *     Set "C_PREDEF=-D __EXAMPLE_GPIO__" in gcc_makefile file. And compile the
 *     app using "make clean/new".
 *     Download image bin to module to run.
 *
 * Author:
 * -------
 * -------
 *
 *============================================================================
 *             HISTORY
 *----------------------------------------------------------------------------
 *
 ****************************************************************************/
#ifdef __UART_TASK__
#include "ql_trace.h"
#include "ql_system.h"
#include "ql_gpio.h"
#include "ql_stdlib.h"
#include "ql_error.h"
#include "ql_uart.h"
#include "ril.h"
#include "ril_util.h"
#include "ql_type.h"
#include "ql_trace.h"
#include "ql_stdlib.h"
#include "ril_gps.h"
#include "ql_gnss.h"
#include "Nema_pro.h"



#define DEBUG_ENABLE 1
#if DEBUG_ENABLE > 0
#define DEBUG_PORT  UART_PORT1
#define DBG_BUF_LEN   512
static char DBG_BUFFER[DBG_BUF_LEN];
#define APP_DEBUG(FORMAT,...) {\
    Ql_memset(DBG_BUFFER, 0, DBG_BUF_LEN);\
    Ql_sprintf(DBG_BUFFER,FORMAT,##__VA_ARGS__); \
    if (UART_PORT2 == (DEBUG_PORT)) \
    {\
        Ql_Debug_Trace(DBG_BUFFER);\
    } else {\
        Ql_UART_Write((Enum_SerialPort)(DEBUG_PORT), (u8*)(DBG_BUFFER), Ql_strlen((const char *)(DBG_BUFFER)));\
    }\
}
#else
#define APP_DEBUG(FORMAT,...)
#endif

#define SERIAL_RX_BUFFER_LEN  2048
static u8 m_RxBuf_Uart[SERIAL_RX_BUFFER_LEN];


void proc_task1(s32 TaskId);

void proc_task2(s32 TaskId);
void proc_task3();


s32 Ql_UART_Write(Enum_SerialPort port, u8* data, u32 writeLen );


static s32 ReadSerialPort(Enum_SerialPort port, /*[out]*/u8* pBuffer, /*[in]*/u32 bufLen)
{
    s32 rdLen = 0;
    s32 rdTotalLen = 0;
    if (NULL == pBuffer || 0 == bufLen)
    {
        return -1;
    }
    Ql_memset(pBuffer, 0x0, bufLen);
    while (1)
    {
        rdLen = Ql_UART_Read(port, pBuffer + rdTotalLen, bufLen - rdTotalLen);
        if (rdLen <= 0)  // All data is read out, or Serial Port Error!
        {
            break;
        }
        rdTotalLen += rdLen;
        // Continue to read...
    }
    if (rdLen < 0) // Serial Port Error!
    {
        APP_DEBUG("<--Fail to read from port[%d]-->\r\n", port);
        return -99;
    }
    return rdTotalLen;
}


static void CallBack_UART_Hdlr(Enum_SerialPort port, Enum_UARTEventType msg, bool level, void* customizedPara)
{
s32 iRet = 0;
   //APP_DEBUG("\r\n it is inside callback_UART Handler\r\n");
   switch (msg)
   {
    case EVENT_UART_READY_TO_READ:
   {
   char* p = NULL;
   s32 totalBytes = ReadSerialPort(port, m_RxBuf_Uart, sizeof(m_RxBuf_Uart));
   if (totalBytes <= 0)
   {
APP_DEBUG("totalBytes = %d.\r\n",totalBytes);
   break;
   }

   APP_DEBUG("given i/p : %s\r\n",m_RxBuf_Uart);

 
   proc_task3();
 
   //APP_DEBUG("Invalid command...\r\n");
   }break;

   case EVENT_UART_READY_TO_WRITE:
   {
   //...
   }break;

   default:
   break;
   }
   
}


/************************************************************************/
/* The entrance for this example application                            */
/************************************************************************/
void proc_main_task(s32 taskId)
{
    s32 ret;
    ST_MSG msg;

    // Register & open UART port
    ret = Ql_UART_Register(UART_PORT1, CallBack_UART_Hdlr, NULL);
    if (ret < QL_RET_OK)
    {
        Ql_Debug_Trace("Fail to register serial port[%d], ret=%d\r\n", UART_PORT1, ret);
    }
    ret = Ql_UART_Open(UART_PORT1, 115200, FC_NONE);
    if (ret < QL_RET_OK)
    {
        Ql_Debug_Trace("Fail to open serial port[%d], ret=%d\r\n", UART_PORT1, ret);
    }
   
    APP_DEBUG("\r\n<-- OpenCPU: UART TASK EXECUTION-->\r\n");

   
     proc_task1(taskId);

    // Start message loop of this task
    while (TRUE)
    {
        Ql_OS_GetMessage(&msg);
        switch(msg.message)
        {
        case MSG_ID_USER_START:
            break;
        default:
            break;
        }
    }
}



//SUB TASK 1
void proc_task1(s32 TaskId)
{

APP_DEBUG("\r\n<-- IT IS INSIDE PROC_TASK1-->\r\n");
Ql_UART_Write(UART_PORT1, m_RxBuf_Uart, sizeof(m_RxBuf_Uart));
proc_task2(TaskId);

}

//SUBTASK2
void proc_task2(s32 TaskId)
{

APP_DEBUG("\r\n<-- IT IS INSIDE PROC_TASK2-->\r\n");
Ql_UART_Write(UART_PORT1, m_RxBuf_Uart, sizeof(m_RxBuf_Uart));

}

void proc_task3()
{

APP_DEBUG("\r\n<-- IT IS INSIDE PROC_TASK3-->\r\n");
Ql_UART_Write(UART_PORT1, m_RxBuf_Uart, sizeof(m_RxBuf_Uart));

}




#endif //__EXAMPLE_GPIO__



Saturday, July 27, 2019

variable declaration in makefiles



printing variable in makefile

@echo the program for compilation is $(C_PREDEF)
@echo $(C_PREDEF)


printing symbols in makefiles
@echo ----------------------------------------------------
@echo ***********************************

Thursday, July 25, 2019

esp32 wrover kit lcd test

/***************************************************
  This is our GFX example for the Adafruit ILI9341 Breakout and Shield
  ----> http://www.adafruit.com/products/1651

  Check out the links above for our tutorials and wiring diagrams
  These displays use SPI to communicate, 4 or 5 pins are required to
  interface (RST is optional)
  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Limor Fried/Ladyada for Adafruit Industries.
  MIT license, all text above must be included in any redistribution
 ****************************************************/


#include "SPI.h"
#include "Adafruit_GFX.h"
#include "WROVER_KIT_LCD.h"

#define min(X, Y) (((X) < (Y)) ? (X) : (Y))

WROVER_KIT_LCD tft;

void setup() {
  Serial.begin(115200);

  tft.begin();
  tft.setRotation(1);

  uint8_t x = 0;
  uint32_t id = tft.readId();
  if(id){
      Serial.println("======= WROVER ST7789V Display Test ========");
  } else {
      Serial.println("======= WROVER ILI9341 Display Test ========");
  }
  Serial.println("============================================");
  Serial.printf("Display ID:      0x%06X\n", id);

  x = tft.readcommand8(WROVER_RDDST);
  Serial.print("Status:          0x"); Serial.println(x, HEX);
  x = tft.readcommand8(WROVER_RDDPM);
  Serial.print("Power Mode:      0x"); Serial.println(x, HEX);
  x = tft.readcommand8(WROVER_RDDMADCTL);
  Serial.print("MADCTL Mode:     0x"); Serial.println(x, HEX);
  x = tft.readcommand8(WROVER_RDDCOLMOD);
  Serial.print("Pixel Format:    0x"); Serial.println(x, HEX);
  x = tft.readcommand8(WROVER_RDDIM);
  Serial.print("Image Format:    0x"); Serial.println(x, HEX);
  x = tft.readcommand8(WROVER_RDDSDR);
  Serial.print("Self Diagnostic: 0x"); Serial.println(x, HEX);
 
  Serial.println(F("Benchmark                Time (microseconds)"));
  delay(10);
  Serial.print(F("Screen fill              "));
  Serial.println(testFillScreen());
  delay(500);

  Serial.print(F("Text                     "));
  Serial.println(testText());
  delay(3000);

  Serial.print(F("Lines                    "));
  Serial.println(testLines(WROVER_CYAN));
  delay(500);

  Serial.print(F("Horiz/Vert Lines         "));
  Serial.println(testFastLines(WROVER_RED, WROVER_BLUE));
  delay(500);

  Serial.print(F("Rectangles (outline)     "));
  Serial.println(testRects(WROVER_GREEN));
  delay(500);

  Serial.print(F("Rectangles (filled)      "));
  Serial.println(testFilledRects(WROVER_YELLOW, WROVER_MAGENTA));
  delay(500);

  Serial.print(F("Circles (filled)         "));
  Serial.println(testFilledCircles(10, WROVER_MAGENTA));

  Serial.print(F("Circles (outline)        "));
  Serial.println(testCircles(10, WROVER_WHITE));
  delay(500);

  Serial.print(F("Triangles (outline)      "));
  Serial.println(testTriangles());
  delay(500);

  Serial.print(F("Triangles (filled)       "));
  Serial.println(testFilledTriangles());
  delay(500);

  Serial.print(F("Rounded rects (outline)  "));
  Serial.println(testRoundRects());
  delay(500);

  Serial.print(F("Rounded rects (filled)   "));
  Serial.println(testFilledRoundRects());
  delay(500);

  Serial.println(F("Done!"));

}


void loop(void) {
  for(uint8_t rotation=0; rotation<4; rotation++) {
    tft.setRotation(rotation);
    testText();
    delay(1000);
  }
}

unsigned long testFillScreen() {
  unsigned long start = micros();
  tft.fillScreen(WROVER_BLACK);
  yield();
  tft.fillScreen(WROVER_RED);
  yield();
  tft.fillScreen(WROVER_GREEN);
  yield();
  tft.fillScreen(WROVER_BLUE);
  yield();
  tft.fillScreen(WROVER_BLACK);
  yield();
  return micros() - start;
}

unsigned long testText() {
  tft.fillScreen(WROVER_BLACK);
  unsigned long start = micros();
  tft.setCursor(0, 0);
  tft.setTextColor(WROVER_WHITE);  tft.setTextSize(1);
  tft.println("Hello World!");
  tft.setTextColor(WROVER_YELLOW); tft.setTextSize(2);
  tft.println(1234.56);
  tft.setTextColor(WROVER_RED);    tft.setTextSize(3);
  tft.println(0xDEADBEEF, HEX);
  tft.println();
  tft.setTextColor(WROVER_GREEN);
  tft.setTextSize(5);
  tft.println("ANIL.DURGAM");
  tft.setTextSize(2);
  tft.println("Embedded systems");
  tft.setTextSize(1);
  tft.println("programming is easy");
  tft.println("once you start working");
  tft.println("you will understand");
  tft.println("start with basics");
  tft.println("of the arduino");
  tft.println("become thopu");
  tft.println("durgam.anil1@gmail.com");
  return micros() - start;
}

unsigned long testLines(uint16_t color) {
  unsigned long start, t;
  int           x1, y1, x2, y2,
                w = tft.width(),
                h = tft.height();

  tft.fillScreen(WROVER_BLACK);
  yield();
 
  x1 = y1 = 0;
  y2    = h - 1;
  start = micros();
  for(x2=0; x2<w; x2+=6) tft.drawLine(x1, y1, x2, y2, color);
  x2    = w - 1;
  for(y2=0; y2<h; y2+=6) tft.drawLine(x1, y1, x2, y2, color);
  t     = micros() - start; // fillScreen doesn't count against timing

  yield();
  tft.fillScreen(WROVER_BLACK);
  yield();

  x1    = w - 1;
  y1    = 0;
  y2    = h - 1;
  start = micros();
  for(x2=0; x2<w; x2+=6) tft.drawLine(x1, y1, x2, y2, color);
  x2    = 0;
  for(y2=0; y2<h; y2+=6) tft.drawLine(x1, y1, x2, y2, color);
  t    += micros() - start;

  yield();
  tft.fillScreen(WROVER_BLACK);
  yield();

  x1    = 0;
  y1    = h - 1;
  y2    = 0;
  start = micros();
  for(x2=0; x2<w; x2+=6) tft.drawLine(x1, y1, x2, y2, color);
  x2    = w - 1;
  for(y2=0; y2<h; y2+=6) tft.drawLine(x1, y1, x2, y2, color);
  t    += micros() - start;

  yield();
  tft.fillScreen(WROVER_BLACK);
  yield();

  x1    = w - 1;
  y1    = h - 1;
  y2    = 0;
  start = micros();
  for(x2=0; x2<w; x2+=6) tft.drawLine(x1, y1, x2, y2, color);
  x2    = 0;
  for(y2=0; y2<h; y2+=6) tft.drawLine(x1, y1, x2, y2, color);

  yield();
  return micros() - start;
}

unsigned long testFastLines(uint16_t color1, uint16_t color2) {
  unsigned long start;
  int           x, y, w = tft.width(), h = tft.height();

  tft.fillScreen(WROVER_BLACK);
  start = micros();
  for(y=0; y<h; y+=5) tft.drawFastHLine(0, y, w, color1);
  for(x=0; x<w; x+=5) tft.drawFastVLine(x, 0, h, color2);

  return micros() - start;
}

unsigned long testRects(uint16_t color) {
  unsigned long start;
  int           n, i, i2,
                cx = tft.width()  / 2,
                cy = tft.height() / 2;

  tft.fillScreen(WROVER_BLACK);
  n     = min(tft.width(), tft.height());
  start = micros();
  for(i=2; i<n; i+=6) {
    i2 = i / 2;
    tft.drawRect(cx-i2, cy-i2, i, i, color);
  }

  return micros() - start;
}

unsigned long testFilledRects(uint16_t color1, uint16_t color2) {
  unsigned long start, t = 0;
  int           n, i, i2,
                cx = tft.width()  / 2 - 1,
                cy = tft.height() / 2 - 1;

  tft.fillScreen(WROVER_BLACK);
  n = min(tft.width(), tft.height());
  for(i=n; i>0; i-=6) {
    i2    = i / 2;
    start = micros();
    tft.fillRect(cx-i2, cy-i2, i, i, color1);
    t    += micros() - start;
    // Outlines are not included in timing results
    tft.drawRect(cx-i2, cy-i2, i, i, color2);
    yield();
  }

  return t;
}

unsigned long testFilledCircles(uint8_t radius, uint16_t color) {
  unsigned long start;
  int x, y, w = tft.width(), h = tft.height(), r2 = radius * 2;

  tft.fillScreen(WROVER_BLACK);
  start = micros();
  for(x=radius; x<w; x+=r2) {
    for(y=radius; y<h; y+=r2) {
      tft.fillCircle(x, y, radius, color);
    }
  }

  return micros() - start;
}

unsigned long testCircles(uint8_t radius, uint16_t color) {
  unsigned long start;
  int           x, y, r2 = radius * 2,
                w = tft.width()  + radius,
                h = tft.height() + radius;

  // Screen is not cleared for this one -- this is
  // intentional and does not affect the reported time.
  start = micros();
  for(x=0; x<w; x+=r2) {
    for(y=0; y<h; y+=r2) {
      tft.drawCircle(x, y, radius, color);
    }
  }

  return micros() - start;
}

unsigned long testTriangles() {
  unsigned long start;
  int           n, i, cx = tft.width()  / 2 - 1,
                      cy = tft.height() / 2 - 1;

  tft.fillScreen(WROVER_BLACK);
  n     = min(cx, cy);
  start = micros();
  for(i=0; i<n; i+=5) {
    tft.drawTriangle(
      cx    , cy - i, // peak
      cx - i, cy + i, // bottom left
      cx + i, cy + i, // bottom right
      tft.color565(i, i, i));
  }

  return micros() - start;
}

unsigned long testFilledTriangles() {
  unsigned long start, t = 0;
  int           i, cx = tft.width()  / 2 - 1,
                   cy = tft.height() / 2 - 1;

  tft.fillScreen(WROVER_BLACK);
  start = micros();
  for(i=min(cx,cy); i>10; i-=5) {
    start = micros();
    tft.fillTriangle(cx, cy - i, cx - i, cy + i, cx + i, cy + i,
      tft.color565(0, i*10, i*10));
    t += micros() - start;
    tft.drawTriangle(cx, cy - i, cx - i, cy + i, cx + i, cy + i,
      tft.color565(i*10, i*10, 0));
    yield();
  }

  return t;
}

unsigned long testRoundRects() {
  unsigned long start;
  int           w, i, i2,
                cx = tft.width()  / 2 - 1,
                cy = tft.height() / 2 - 1;

  tft.fillScreen(WROVER_BLACK);
  w     = min(tft.width(), tft.height());
  start = micros();
  for(i=0; i<w; i+=6) {
    i2 = i / 2;
    tft.drawRoundRect(cx-i2, cy-i2, i, i, i/8, tft.color565(i, 0, 0));
  }

  return micros() - start;
}

unsigned long testFilledRoundRects() {
  unsigned long start;
  int           i, i2,
                cx = tft.width()  / 2 - 1,
                cy = tft.height() / 2 - 1;

  tft.fillScreen(WROVER_BLACK);
  start = micros();
  for(i=min(tft.width(), tft.height()); i>20; i-=6) {
    i2 = i / 2;
    tft.fillRoundRect(cx-i2, cy-i2, i, i, i/8, tft.color565(0, i, 0));
    yield();
  }

  return micros() - start;
}

output:



Sunday, July 21, 2019

rs485 to hm-trp-rs485 connections and baud rate setting

hm-trp rs 485  have mainly 4 pins vdd,A,B,Gnd.
usb to rs 485 have (which one i have with me) 3 pins A,B,Gnd.

after some serious struggle i find the how to connect and how to test.
for the gui there is small gui related software.









module is set fine.
after that remove the all connection and test. download gui related software from here


Tuesday, July 16, 2019

RFM95 with arduino uno Transmitter and receiver

Before starting to  test communicate with Rfm95 with Arduino uno download radio head library

radio head library for arduino uno with rfm
https://drive.google.com/open?id=1iBQWCOm13X3bdDKEcy0czGebPDz_PqQ-

RFM95 with arduino uno connections:



ARDUINO UNO
RFM 95
Gnd
Gnd
3.3v
3.3v
D5
reset
D2
DIO 0
D3
DIO1
D13(SCK)
SCK
D12(MISO)
MISO
D11(MOSI)
MOSI
D10(SS)
NSS



NOTE:
LEVEL SHIFTER FOR BETTER OUTPUT




sender side code:

#include <SPI.h>
#include <RH_RF95.h>

RH_RF95 rf95;

int led = 9;

void setup()
{
  pinMode(led, OUTPUT);   
  Serial.begin(9600);
  while (!Serial) ; // Wait for serial port to be available
  if (!rf95.init())
    Serial.println("init failed");

}

void loop()
{
  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("request: ", buf, len);
      Serial.print("got request: ");
      Serial.println((char*)buf);
   
//      Serial.print("RSSI: ");
//      Serial.println(rf95.lastRssi(), DEC);
   
   
      /***************************************/
      // Send a reply
      /***************************************/
    char data[32]="";
   int availableBytes = Serial.available();
   for(int i=0; i<availableBytes; i++)
    {   
        data[i]=Serial.read();
    }
      rf95.send(data, sizeof(data));
      rf95.waitPacketSent();
      Serial.println("Sent::");
      Serial.print(data);
       digitalWrite(led, LOW);
     
    }
    else
    {
      Serial.println("recv failed");
    }
  }
  delay(100);
}


receiver side code:

// rf95_client.pde

#include <SPI.h>
#include <RH_RF95.h>

int led = 9;

RH_RF95 rf95;


void setup()
{
  pinMode(led, OUTPUT); 

  Serial.begin(9600);
  while (!Serial) ; // Wait for serial port to be available
  if (!rf95.init())
    Serial.println("init failed");
}

void loop()
{
  rfm95_uart();

}

void rfm95_uart()
{
  Serial.println("Sending to rf95_server::");


  char data[32]="";
   int availableBytes = Serial.available();
   for(int i=0; i<availableBytes; i++)
    {   
        data[i]=Serial.read();
    }
      rf95.send(data, sizeof(data));
      rf95.waitPacketSent();
      Serial.println("Sent::");
      Serial.print(data);
       digitalWrite(led, LOW);

  uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
  uint8_t len = sizeof(buf);


  if (rf95.waitAvailableTimeout(3000))
  {
    // Should be a reply message for us now 
    if (rf95.recv(buf, &len))
   {
      Serial.print("got reply: ");
      Serial.println((char*)buf);
//      Serial.print("RSSI: ");
//      Serial.println(rf95.lastRssi(), DEC); 
    }

    else
    {
      Serial.println("recv failed");
    }
  }

  else
  {
    Serial.println("No reply, is rf95_server running?");
  }
  delay(400);


  }
out put:




after some modification::
send code:
#include <SPI.h>
#include <RH_RF95.h>

RH_RF95 rf95;

int led = 9;

void setup()
{
  pinMode(led, OUTPUT);   
  Serial.begin(9600);
  while (!Serial) ; // Wait for serial port to be available
  if (!rf95.init())
    Serial.println("init failed");
}

void loop()
{
  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("request: ", buf, len);
      Serial.print("got request: ");
      Serial.println((char*)buf);
      /***************************************/
      // Send a reply
      /***************************************/
    char data[32]="";
   int availableBytes = Serial.available();
   for(int i=0; i<availableBytes; i++)
    {   
        data[i]=Serial.read();
    }
      rf95.send(data, sizeof(data));
      rf95.waitPacketSent();
      Serial.println("Sent::");
      Serial.print(data);
       digitalWrite(led, LOW);
    }
    else
    {
      Serial.println("recv failed");
    }
  }
  delay(100);

}

Receiver code:
// rf95_client.pde

#include <SPI.h>
#include <RH_RF95.h>

int led = 9;

RH_RF95 rf95;


void setup()
{
  pinMode(led, OUTPUT); 

  Serial.begin(9600);
  while (!Serial) ; // Wait for serial port to be available
  if (!rf95.init())
    Serial.println("init failed");
}

void loop()
{
  rfm95_uart();

}

void rfm95_uart()
{
  //Serial.println("Sending to rf95_server::");
  char data[32]="";
   int availableBytes = Serial.available();
   for(int i=0; i<availableBytes; i++)
    {   
        data[i]=Serial.read();
    }
      rf95.send(data, sizeof(data));
      rf95.waitPacketSent();
      Serial.println("Sent::");
      Serial.print(data);
       digitalWrite(led, LOW);

  uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
  uint8_t len = sizeof(buf);
  if (rf95.waitAvailableTimeout(3000))
  {
    if (rf95.recv(buf, &len))
   {
      Serial.print("got reply: ");
      Serial.println((char*)buf);
    }

    else
    {
      Serial.println("recv failed");
    }
  }
  else
  {
    Serial.println("No reply, is rf95_server running?");
  }
  delay(400);
  }



Monday, July 15, 2019

Node MCU with WIFI scanning

/*
    This sketch demonstrates how to scan WiFi networks.
    The API is almost the same as with the WiFi Shield library,
    the most obvious difference being the different file you need to include:
*/
#include "ESP8266WiFi.h"

void setup() {
  Serial.begin(115200);

  // Set WiFi to station mode and disconnect from an AP if it was previously connected
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);

  Serial.println("Setup done");
}

void loop() {
  Serial.println("scan start");

  // WiFi.scanNetworks will return the number of networks found
  int n = WiFi.scanNetworks();
  Serial.println("scan done");
  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));
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i));
      Serial.print(")");
      Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE) ? " " : "*");
      delay(10);
    }
  }
  Serial.println("");

  // Wait a bit before scanning again
  delay(5000);
}

output:


Sunday, July 14, 2019

SHT31 Temparature and Humidity sensor with arduino uno


#include <Arduino.h>
#include <Wire.h>
#include "Adafruit_SHT31.h"

Adafruit_SHT31 sht31 = Adafruit_SHT31();

void setup() {
  Serial.begin(9600);

  while (!Serial)
    delay(10);     // will pause Zero, Leonardo, etc until serial console opens

  Serial.println("SHT31 test");
  if (! sht31.begin(0x44)) {   // Set to 0x45 for alternate i2c addr
    Serial.println("Couldn't find SHT31");
    while (1) delay(1);
  }
}


void loop() {
  float t = sht31.readTemperature();
  float h = sht31.readHumidity();

  if (! isnan(t)) {  // check if 'is not a number'
    Serial.print("Temp *C = "); Serial.println(t);
  } else {
    Serial.println("Failed to read temperature");
  }
 
  if (! isnan(h)) {  // check if 'is not a number'
    Serial.print("Hum. % = "); Serial.println(h);
  } else {
    Serial.println("Failed to read humidity");
  }
  Serial.println();
  delay(1000);
}

output::

Tuesday, July 9, 2019

c interview question25

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int x=55, y=17;
    printf("%d\n",func(x,y));
    return 0;
}
func (int x, int y)
{
    int q=0;
    if (x<y)
        return 0;
    else
        return func(x-y,y)+1;
}


output::
3

c interview question24

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a=7,b=8;
    printf("%d\n",fune(a,b)) ;
    return 0;
}

fune(int x,int y)
{
    if (x==0)
        return y;
    else
        fune(--x, ++y);
}


output::
15

c interview question 23

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a=2,b=6;
    printf("%d\t",funcl(a,b));
    printf("%d\n",func2(a,b));
    return 0;
}
funcl(int a, int b)
{
    int i,s=0;
    for(i=a;i<=b;i++)
    {s=s+i*i;}
return s;
}
func2(int a, int b)
{
    int s;
    if (a<b)
        s=a*a+func2(a+1,b);
    else
        s=a*a;
}


output::
90      90

c interview question 22

#include <stdio.h>
#include <stdlib.h>

int main()
{
   int n=8;
    printf("%d\n",func(n));
    return 0;
}



func(int n)
{
    if(n==0)
        return 0;
    else
        return(n+func(n-1));
}

output::
36

c interview question 21

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i=0,k=3;
    i+=func(k);
    i+=func(k);
    i+=func(k);
    printf("%d\n",i);
    return 0;
}

func(int k)
{
    static int m=2;
    m=m+k;
    return m;
}

output::
24


explanation:
1st->k=3,m=5,i=5
2nd->k=3,m=8,i=13
3rd->k=3,m=11,i=24

c interview question20

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a=2,b=5;
    a=func(a+b,a-b);
    printf("%d\n",a);
    return 0;
}

func (int x, int y)
{ return x+y, x-y;}

output::
10

c interview questions 19

#include <stdio.h>
#include <stdlib.h>


int a=5;
void func(void );

int main()
{
    func() ;
    printf ("%d\n", a);
    return 0;
}

void func (void)
{
int a=2;
printf ("%d\t", a);
}

output::
2       5

c interview questions18

#include <stdio.h>
#include <stdlib.h>

void func (int a, int b);
int main()
{
    int i=5,j=10;
    func(i/2,j%3) ;

    return 0;
}
void func(int a,int b)
{
    a=a/2;
    b--;
    printf("%d\t",a+b) ;
}

output::
1

c interview question17

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int x;
    x=func(2,3,5);
    printf("%d\n",x);
    return 0;
}
func(int a ,int b, int c)
{
    return (a,b,c);
}

output:
5

c interview question16

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i=2,j=3;
    printf("%d\n",func(i,j));
    return 0;
}
func(int a ,int b)
{
    a=a-5;
    b++;
    return(!a+--b);
}
output::
3

c interview questions 15

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i=10,k;
    for(;;)
    {
        k=mult(i);
        if(--i<5)
            break;
    }
    printf("k=%d\n",k);
    return 0;
}
mult(int j)
{
    j*=j;
    return j;
}

output:
k=25

c interview questions14

#include <stdio.h>
#include <stdlib.h>


void func(void);
int main()
{
    int i=5;
    for(i=i+1;i<8;i++)
        func();
    return 0;
}

void func (void)
{
    int j;
    for(j=1;j<3;j++)
        printf("%d\t",++j);
}

output::
2       2

Monday, July 8, 2019

c interview questions13

#include <stdio.h>
#include <stdlib.h>


void disp(int, int);
int main()
{
    int x=15;
    float y=290.5;
    disp(x,y) ;
    return 0;
}

void disp(int a, int b)
{
    printf("%d %d\n",a,b);
}


output:
15 290

c interview questions 12

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int x=5;
    func1(x) ;

    return 0;
}

func1(int a)
{
    printf("Value of a=%d\n",a);
    if(a>0)
        {func2(--a);}
}

func2(int b)
{
    printf("Value of b=%d\n",b);
    if (b>0)
       {func1(--b);}
}

output::

Value of a=5
Value of b=4
Value of a=3
Value of b=2
Value of a=1
Value of b=0

c interview questions 11

#include <stdio.h>
#include <stdlib.h>

int main()
{
   int func(int a,int b);
   {
       return (a+b);
   }
    int c;
    c=func(3,5) ;
    printf("%d",c) ;
}

output::

//We'll get errors because a function definition can't be written inside definition of another function.

c interview question10

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int n=5;
    printf("%d\n",func(n));
    return 0;
}
func (int n)
{ return(n+sqr(n-2)+cube(n-3));}
sqr (int x)
{ return (x*x); }
cube(int x)
{ return (x*x*x);}


output::
22

c interview question9

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int varl=12, var2=35;
    printf("%d",max(varl,var2));
    return 0;
}



int max (int x, int y)
{
    x>y? return x: return y;
}

output::
Error: Expression syntax
The operands of conditional operator should be expressions, but return x and return y are not
expressions.

c interview question8

#include <stdio.h>
#include <stdlib.h>

func(int x,int y);
int main()
{
    int p=func(5,6);
    printf("%d",p) ;
    return 0;
}
func(int x,int y)
{
    int x=2;
    return x*y;
}

output::

error:: multiple declaration of x

c interview question7

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int s;
    s=func(2,3,6);
    printf("%d\n",s);
    return 0;
}


int func (int a, int b)
{
    return (a+b);

}

output::
5

C interview questions6

#include <stdio.h>
#include <stdlib.h>

void main ()
{

    int s;
    s=func(2,3);
    printf("%d\n",s);
}
int func(int a,int b,int c)
{
        c=4;
    return (a+b+c);
}
output ::

9

c interview questions4

#include <stdio.h>
#include <stdlib.h>

void main()
{
    int x=6;
    x=func();
    printf("%d\n",x);
}

int func (int a)
{
    a=a*2;
}


output ::
1

gtts example using python

from gtts import gTTS
import os
tts = gTTS('hello world')
tts.save('hello.mp3')
os.system("hello.mp3")

simple car game using pygame library

#this is game originally developed by another developer i got this on the internet
import pygame,random, sys ,os,time
from pygame.locals import *

WINDOWWIDTH = 800
WINDOWHEIGHT = 600
TEXTCOLOR = (255, 255, 255)
BACKGROUNDCOLOR = (0, 0, 0)
FPS = 40
BADDIEMINSIZE = 10
BADDIEMAXSIZE = 40
BADDIEMINSPEED = 8
BADDIEMAXSPEED = 8
ADDNEWBADDIERATE = 6
PLAYERMOVERATE = 5
count=3

def terminate():
    pygame.quit()
    sys.exit()

def waitForPlayerToPressKey():
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                terminate()
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE: #escape quits
                    terminate()
                return

def playerHasHitBaddie(playerRect, baddies):
    for b in baddies:
        if playerRect.colliderect(b['rect']):
            return True
    return False

def drawText(text, font, surface, x, y):
    textobj = font.render(text, 1, TEXTCOLOR)
    textrect = textobj.get_rect()
    textrect.topleft = (x, y)
    surface.blit(textobj, textrect)

# set up pygame, the window, and the mouse cursor
pygame.init()
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('car race')
pygame.mouse.set_visible(False)

# fonts
font = pygame.font.SysFont(None, 30)

# sounds
gameOverSound = pygame.mixer.Sound('music/crash.wav')
pygame.mixer.music.load('music/car.wav')
laugh = pygame.mixer.Sound('music/laugh.wav')


# images
playerImage = pygame.image.load('image/car1.png')
car3 = pygame.image.load('image/car3.png')
car4 = pygame.image.load('image/car4.png')
playerRect = playerImage.get_rect()
baddieImage = pygame.image.load('image/car2.png')
sample = [car3,car4,baddieImage]
wallLeft = pygame.image.load('image/left.png')
wallRight = pygame.image.load('image/right.png')


# "Start" screen
drawText('Press any key to start the game.', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3))
drawText('And Enjoy', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3)+30)
pygame.display.update()
waitForPlayerToPressKey()
zero=0
if not os.path.exists("data/save.dat"):
    f=open("data/save.dat",'w')
    f.write(str(zero))
    f.close() 
v=open("data/save.dat",'r')
topScore = int(v.readline())
v.close()
while (count>0):
    # start of the game
    baddies = []
    score = 0
    playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50)
    moveLeft = moveRight = moveUp = moveDown = False
    reverseCheat = slowCheat = False
    baddieAddCounter = 0
    pygame.mixer.music.play(-1, 0.0)

    while True: # the game loop
        score += 1 # increase score

        for event in pygame.event.get():
           
            if event.type == QUIT:
                terminate()

            if event.type == KEYDOWN:
                if event.key == ord('z'):
                    reverseCheat = True
                if event.key == ord('x'):
                    slowCheat = True
                if event.key == K_LEFT or event.key == ord('a'):
                    moveRight = False
                    moveLeft = True
                if event.key == K_RIGHT or event.key == ord('d'):
                    moveLeft = False
                    moveRight = True
                if event.key == K_UP or event.key == ord('w'):
                    moveDown = False
                    moveUp = True
                if event.key == K_DOWN or event.key == ord('s'):
                    moveUp = False
                    moveDown = True

            if event.type == KEYUP:
                if event.key == ord('z'):
                    reverseCheat = False
                    score = 0
                if event.key == ord('x'):
                    slowCheat = False
                    score = 0
                if event.key == K_ESCAPE:
                        terminate()
           

                if event.key == K_LEFT or event.key == ord('a'):
                    moveLeft = False
                if event.key == K_RIGHT or event.key == ord('d'):
                    moveRight = False
                if event.key == K_UP or event.key == ord('w'):
                    moveUp = False
                if event.key == K_DOWN or event.key == ord('s'):
                    moveDown = False

           

        # Add new baddies at the top of the screen
        if not reverseCheat and not slowCheat:
            baddieAddCounter += 1
        if baddieAddCounter == ADDNEWBADDIERATE:
            baddieAddCounter = 0
            baddieSize =30
            newBaddie = {'rect': pygame.Rect(random.randint(140, 485), 0 - baddieSize, 23, 47),
                        'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),
                        'surface':pygame.transform.scale(random.choice(sample), (23, 47)),
                        }
            baddies.append(newBaddie)
            sideLeft= {'rect': pygame.Rect(0,0,126,600),
                       'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),
                       'surface':pygame.transform.scale(wallLeft, (126, 599)),
                       }
            baddies.append(sideLeft)
            sideRight= {'rect': pygame.Rect(497,0,303,600),
                       'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),
                       'surface':pygame.transform.scale(wallRight, (303, 599)),
                       }
            baddies.append(sideRight)
           
           

        # Move the player around.
        if moveLeft and playerRect.left > 0:
            playerRect.move_ip(-1 * PLAYERMOVERATE, 0)
        if moveRight and playerRect.right < WINDOWWIDTH:
            playerRect.move_ip(PLAYERMOVERATE, 0)
        if moveUp and playerRect.top > 0:
            playerRect.move_ip(0, -1 * PLAYERMOVERATE)
        if moveDown and playerRect.bottom < WINDOWHEIGHT:
            playerRect.move_ip(0, PLAYERMOVERATE)
       
        for b in baddies:
            if not reverseCheat and not slowCheat:
                b['rect'].move_ip(0, b['speed'])
            elif reverseCheat:
                b['rect'].move_ip(0, -5)
            elif slowCheat:
                b['rect'].move_ip(0, 1)

       
        for b in baddies[:]:
            if b['rect'].top > WINDOWHEIGHT:
                baddies.remove(b)

        # Draw the game world on the window.
        windowSurface.fill(BACKGROUNDCOLOR)

        # Draw the score and top score.
        drawText('Score: %s' % (score), font, windowSurface, 128, 0)
        drawText('Top Score: %s' % (topScore), font, windowSurface,128, 20)
        drawText('Rest Life: %s' % (count), font, windowSurface,128, 40)
       
        windowSurface.blit(playerImage, playerRect)

       
        for b in baddies:
            windowSurface.blit(b['surface'], b['rect'])

        pygame.display.update()

        # Check if any of the car have hit the player.
        if playerHasHitBaddie(playerRect, baddies):
            if score > topScore:
                g=open("data/save.dat",'w')
                g.write(str(score))
                g.close()
                topScore = score
            break

        mainClock.tick(FPS)

    # "Game Over" screen.
    pygame.mixer.music.stop()
    count=count-1
    gameOverSound.play()
    time.sleep(1)
    if (count==0):
     laugh.play()
     drawText('Game over', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
     drawText('Press any key to play again.', font, windowSurface, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 30)
     pygame.display.update()
     time.sleep(2)
     waitForPlayerToPressKey()
     count=3
     gameOverSound.stop()



download rar file here

c interview questions3

#include <stdio.h>
#include <stdlib.h>

void func(int a,int b);
void main( )
{
    int x;
    x=func(2,3);
}
void func(int a,int b)
{
    int s;
    s=a+b;
    return;
}

output:
error: void value not ignored as it ought to be


explanation: void functions cant gives the return values .so in main "func" is  returning the value that will gives the error

c interview questions2

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i=9;
    if(i==9)
    {
        int i=25;
    }
    printf("i=%d",i);
   // printf("Hello world!\n");
    return 0;
}


output:
i=9


explanation:in if block it is again defined but it takes like function inside declaration

c interview questions1

#include <stdio.h>
#include <stdlib.h>

void func (void);
void main( )
{
    printf("first print\n");
    goto abc;
}
void func (void)
{
    abc:
    printf("Barilly\n");
}


output:

error:label abc is used but not defined

LCM and HCF of the two numbers in c programming

#include <stdio.h>
#include <stdlib.h>


int m, n;
main( )
{
    int x,y;
    printf ("Enter two numbers ");
    scanf ("%d %d·" , &x, &y);
    printf ("RCF of %d and %d is %d\n", x, y, hcf (x, y) );
    m=x;n=y;
    printf ("LCM of %d and %d is %d\n", x, y, lcm (x, y) );
}
int hcf(int a, int b)
{
    if(a==b)
        return(b);
    else if (a<b)
        hcf(a,b-a);
    else
        hcf(a-b,b);
}
int lcm(int a, int b)
{
    if (a==b)
        return(b);
    else if(a<b)
        lcm(a+m,b);
    else
        lcm(a,b+n);
}


output:

Enter two numbers 12
15
RCF of 12 and 15 is 3
LCM of 12 and 15 is 60

program to find the sum of series in c language

#include <stdio.h>
#include <stdlib.h>

long intfact (int num);
double power (float x, int n);
double series (float x, int n);
double rseries (float x, int n);

void main()
{

    float x;
    int n;
    printf ("Enter x:");
    scanf("%f",&x);
    printf ("Enter number of terms\n");
    scanf ("%d", &n);
    printf("Iterative %lf\n",series(x,n));
    printf("Recursive %lf\n",series(x,n));
}

long int fact (int num)
{


    int i;
    long int f=1;
    for(i=1;i<=num;i++)
        f=f*i;
    return f;
}
double power (float x, int n)
{
    int i;
    float p=1;
    for(i=1;i<=n;i++)
        p=p*x;
    return p;
}

double series (float x, int n)
{
    int i,j,sign=1;
    float term, sum;
    for(i=1;i<=n;i++)

    sign=(i%2==0)?-1:1;
    j=2*i-1;
    term=sign*power(x,j)/fact(j);
    sum+=term;
    return sum;
}
double rseries( float x, int n)
{
    int sign=1;
    float term, sum;
    if(n==0)
        sum=0;
    else
    {
        sign=(n%2==0)?-1:1;
        term=sign*power(x,2*n-1)/fact(2*n-1);
        sum=term+rseries(x,n-1);
        return sum;
    }
}

decimal to binary,octal and hexadecimal conversion in c language

#include<stdio.h>
#include <string.h>

void convert(int, int);
main ( )
{
    int num, base;
    int choice;
while(1)
{
    printf("l.Binary\n") ;
    printf("2.0ctal\n") ;
    printf("3.Hexadecimal\n") ;
    printf("4.Exit\n") ;
    printf ("Enter your choice\n") ;
    scanf ("%d",&choice);
    switch(choice)
    {
        case 1:
            base=2;
            break;
        case 2:
            base=8;
            break;
        case 3:
            base=16;
            break;
        case 4:
            exit(1) ;
        default:
            printf ("Wrong choice\n");
            continue;

    }
    printf ("Enter the number in decimal: ");
    scanf("%d",&num) ;
    convert(num,base) ;
    printf ("\n") ;
}
}


void convert (int num, int base)
{
    int rem;
    rem=num%base;
    num/=base;
    if (num>0)
        convert (num,base);
    if(rem<10)
        printf("%d",rem);
    else
        printf("%c",rem-10+'A');
}

out put:
l.Binary
2.0ctal
3.Hexadecimal
4.Exii
Enter your choice 1
Enter the number in decimal: 12
1100

l.Binary
2.0ctal
3.Hexadecimal
4.Exii
Enter your choice 2
Enter the number in decimal: 12
14

l.Binary
2.0ctal
3.Hexadecimal
4.Exii
Enter your choice 3
Enter the number in decimal: 12
C

number divisible by 11 or not in the c programming

#include <stdio.h>
#include <stdlib.h>

void test (long int x);
main ( )
{
    long int num;
    printf("Enter the numher to be tested ");
    scanf("%ld",&num);
    test(num) ;
}
void test(long int n)
{
    int s1=0, s2=0, k;
    while(n>0)
    {
        s1+=n%10;
        n/=10;
        s2+=n%10;
        n/=10;
    }
    k=s1>s2? (s1-s2) : (s2-s1) ;
    if(k>10)
        test(k);
    else if(k==0)
        printf ("The number is divisible by 11 \n") ;
    else
        printf("The number is not divisibl~ by 11\n");
}

out put ::
Enter the numher to be tested 121
The number is divisible by 11

Enter the numher to be tested 12345
The number is not divisibl~ by 11




reverse of the given number

#include<stdio.h>
#include <string.h>

void reverse (long int n);
void main ( )
{
    long int num;
    printf ("Enter number ");
    scanf("%ld",&num);
    reverse(num);
    printf("\n");
}
void reverse (long int n)
{
    int rem;

    if(n==0)
        return;
    else
    {
        rem=n%10;
    printf("%d",rem);
        n/=10;
    reverse(n) ;
    }

}


output:

Enter number 12345
54321

Saturday, July 6, 2019

Reading and Writing files in python

""" ***********************************************
programming Language :Python
Tool(IDE) used :Anaconda -> Spider
started date:06-07-2019
latest modified date:06-07-2019
version:1.0
created by:ANIL DURGAM
*****************************************************"""
fred=open("hello","w")
fred.write("hello world")
fred.close()
read_file=open("hello","r")
file_read=read_file.read()
read_file.close()
print(file_read)

list and tuple function usage in python

""" ***********************************************
programming Language :Python
Tool(IDE) used :Anaconda -> Spider
started date:06-07-2019
latest modified date:06-07-2019
version:1.0
created by:ANIL DURGAM
*****************************************************"""
FoodTuple=("egg","bread","chicken")
print(FoodTuple)
FoodList=list(FoodTuple)
print(FoodList)
newfoodtuple=tuple(FoodList)
print(newfoodtuple)


output:
('egg', 'bread', 'chicken')
['egg', 'bread', 'chicken']
('egg', 'bread', 'chicken')

immutable type in python

firstTuple[0]="EGG"
print(firstTuple)

output::

NameError: name 'firstTuple' is not defined

example 2:

firstTuple="EGG"
print(firstTuple)

out put:
EGG


sub string in python


""" ***********************************************
programming Language :Python
Tool(IDE) used :Anaconda -> Spider
started date:06-07-2019
latest modified date:06-07-2019
version:1.0
created by:ANIL DURGAM

*****************************************************"""


word="pig"
pigLatinword=word[1:]+word[0]+"ay"
print(pigLatinword)
print(word[0])
print(word[1])
print(word[2])
word1="pygame"
print(word1[1:])
print(word1[2:])
print(word1[0:])

Friday, July 5, 2019

CALCULATOR PROGRAM USING TKINTER IN PYTHON


""" ***********************************************
programming Language :Python
Tool(IDE) used :Anaconda -> Spider
started date:03-07-2019
latest modified date:06-07-2018
version:1
created by:ANIL DURGAM

*****************************************************"""


from tkinter import *


# globally declare the expression variable

expression = ""


# Function to update expressiom

# in the text entry box

def press(num):

 # point out the global expression variable

 global expression

 # concatenation of string

 expression = expression + str(num)
 # update the expression by using set method

 equation.set(expression)
# Function to evaluate the final expression

def equalpress():

 # Try and except statement is used

 # for handling the errors like zero

 # division error etc.

 # Put that code inside the try block

 # which may generate the error

 try:

  global expression

  # eval function evaluate the expression

  # and str function convert the result

  # into string

  total = str(eval(expression))

  equation.set(total)
  # initialze the expression variable

  # by empty string

  expression = ""

 # if error is generate then handle

 # by the except block

 except:

  equation.set(" error ")

  expression = ""

# Function to clear the contents

# of text entry box

def clear():

 global expression

 expression = ""

 equation.set("")

# Driver code

if __name__ == "__main__":

 # create a GUI window
 gui = Tk()
 # set the background colour of GUI window

 gui.configure(background="light green")
 # set the title of GUI window

 gui.title("Calculator v1.0")
 # set the configuration of GUI window

 #gui.geometry("265x125")
 gui.geometry("360x180")

 # StringVar() is the variable class

 # we create an instance of this class

 equation = StringVar()
 # create the text entry box for

 # showing the expression .

 expression_field = Entry(gui, textvariable=equation)
 # grid method is used for placing

 # the widgets at respective positions

 # in table like structure .

 expression_field.grid(columnspan=6, ipadx=140)#ipadx=80

 equation.set('enter your expression')

 # create a Buttons and place at a particular

 # location inside the root window .

 # when user press the button, the command or

 # function affiliated to that button is executed .

 button1 = Button(gui, text=' 1 ', fg='black', bg='white',

     command=lambda: press(1), height=2, width=7)

 button1.grid(row=2, column=0)



 button2 = Button(gui, text=' 2 ', fg='black', bg='white',

     command=lambda: press(2), height=2, width=7)

 button2.grid(row=2, column=1)



 button3 = Button(gui, text=' 3 ', fg='black', bg='white',

     command=lambda: press(3), height=2, width=7)

 button3.grid(row=2, column=2)



 button4 = Button(gui, text=' 4 ', fg='black', bg='white',

     command=lambda: press(4), height=2, width=7)

 button4.grid(row=3, column=0)



 button5 = Button(gui, text=' 5 ', fg='black', bg='white',

     command=lambda: press(5), height=2, width=7)

 button5.grid(row=3, column=1)



 button6 = Button(gui, text=' 6 ', fg='black', bg='white',

     command=lambda: press(6), height=2, width=7)

 button6.grid(row=3, column=2)



 button7 = Button(gui, text=' 7 ', fg='black', bg='white',

     command=lambda: press(7), height=2, width=7)

 button7.grid(row=4, column=0)



 button8 = Button(gui, text=' 8 ', fg='black', bg='white',

     command=lambda: press(8), height=2, width=7)

 button8.grid(row=4, column=1)



 button9 = Button(gui, text=' 9 ', fg='black', bg='white',

     command=lambda: press(9), height=2, width=7)

 button9.grid(row=4, column=2)



 button0 = Button(gui, text=' 0 ', fg='black', bg='white',

     command=lambda: press(0), height=2, width=7)

 button0.grid(row=5, column=0)



 plus = Button(gui, text=' + ', fg='black', bg='white',

    command=lambda: press("+"), height=2, width=7)

 plus.grid(row=2, column=3)



 minus = Button(gui, text=' - ', fg='black', bg='white',

    command=lambda: press("-"), height=2, width=7)

 minus.grid(row=3, column=3)



 multiply = Button(gui, text=' * ', fg='black', bg='white',

     command=lambda: press("*"), height=2, width=7)

 multiply.grid(row=4, column=3)



 divide = Button(gui, text=' / ', fg='black', bg='white',

     command=lambda: press("/"), height=2, width=7)

 divide.grid(row=5, column=3)



 equal = Button(gui, text=' = ', fg='black', bg='white',

    command=equalpress, height=2, width=7)

 equal.grid(row=5, column=2)



 clear = Button(gui, text='Clear', fg='black', bg='white',

    command=clear, height=2, width=7)

 clear.grid(row=5, column='1')



 # start the GUI

 gui.mainloop()



led blinking program for pic16f877A

#include <htc.h>
#include

#define _XTAL_FREQ 8000000

void main()
{
  TRISB=0X00;
  PORTB=0X00;
  while(1)
  {
    PORTB=0XFF;
    __delay_ms(1000);
    PORTB=0X00;
    __delay_ms(1000);
  }
}

Thursday, July 4, 2019

print the pascal triangle in c language


#include <stdio.h>
#include <stdlib.h>

long factorial(int);
long comb(int,int);

int main()
{
    int i,j,k;
    printf ("Enter number of rows for pascal triangles\n");
    scanf ("%d", &k) ;
    for(i=0;i<k;i++)
    {
        for(j=0;j<=i;j++)
        printf("%5ld",comb(i,j));
        printf("\n") ;
    }
}
long comb(int n,int r)
{

    long c;
    c=factorial(n)/(factorial(r)*factorial(n-r));
    return c;
}
long factorial (int k)
{
    long fact=1;
    while(k>0)
    {
        fact*=k;
        k--;
    }
    return fact;
}


output:
Enter number of rows for pascal triangles
5
    1
    1    1
    1    2    1
    1    3    3    1
    1    4    6    4    1

python class topic video