martes, 6 de junio de 2017

Switch With dsPIC30F4013


Diagram:
Code (XC16 Compiler):
#include <xc.h>
#include <libpic30.h>
 
// Configuration settings
_FOSC(CSW_FSCM_OFF & FRC_PLL16); // Fosc=16x7.5MHz, i.e. 30 MIPS
_FWDT(WDT_OFF);                  // Watchdog timer off
_FBORPOR(MCLR_DIS);              // Disable reset pin
 
int main(void)
{
    // Make RD0 a digital output and RD1 as input
    _TRISD0 = 0;
    _TRISD1 = 1;
    
    // Blink LED on RD0
    while(1)
    {
        if (_RD1 == 1) {
        _LATD0 = 1;
        __delay32(15000000);

        }
        else {
        _LATD0 = 0;
        __delay32(15000000);
        }
    }
}


_______________________________________________________________________

  Projects With dsPIC30F2010 And dsPIC30F4013

http://guillengap.blogspot.com/2016/07/ebook-projects-with-dspic30f2010-and.html


https://www.amazon.com/dp/B01F4YBCHG

https://www.amazon.com/Guillermo%20Perez/e/B01EZOTUVQ/

guillengap@gmail.com

sábado, 3 de junio de 2017

Thermostat With PIC16F887


Diagram:

Code:

#include <16f887.h>
#device ADC=10       
#FUSES XT,NOWDT
#use delay(clock = 4000000)
#define use_portb_lcd TRUE
#include 
#use fast_IO(C)      

#byte trisb=0x86
#byte portb=0x06
#byte trisc=0x87
#byte portc=0x07

void main()
{
   trisc=0b00000000; 
   bit_clear(TRISC,0);         // C0 as output
   bit_clear(TRISC,1);         // C1 as output   
   int16 q;
   float p;
   setup_adc_ports(sAN0);          //Channel 0 
   setup_adc(ADC_CLOCK_DIV_32);    //Clock RC
do
{
     set_adc_channel(0);           // Channel 0
      delay_us(20);
      q = read_adc();                 
      p = 5.0 * 100 * q / 1024.0;           //Conversion
      lcd_init(); // start LCD
      lcd_gotoxy(5,1);
      printf(lcd_putc, "\f      TEMPERATURE  ");
      printf(lcd_putc, "\n        %01.2f C", p);

      if (p >= 30)
      {
         output_high(PIN_C0);                            //turn on FAN
         output_high(PIN_C1);                            //turn on LED        
         delay_ms(500);
      }
      else          
      {
         output_low(PIN_C0);                             //turn off FAN
         output_low(PIN_C1);                             //turn off LED   
         delay_ms(500);
      }
}
while(true);
}


_______________________________________________________________________

 Projects With Microcontrollers And PICC

http://guillengap.blogspot.com/2016/07/ebook-projects-with-microcontrollers.html


https://www.amazon.com/dp/B01EZOMGZS

https://www.amazon.com/Guillermo%20Perez/e/B01EZOTUVQ/

guillengap@gmail.com

jueves, 18 de mayo de 2017

Mega 2560 Projects


1. Mega 2560 And Visible Light Communication With a Laser

Diagram:
Code:
int lightPin = 0;  //define a pin for Photo resistor
int led=13;     //define a pin for LED

void setup()
{
    Serial.begin(9600);  //Begin serial communcation
    pinMode( led, OUTPUT );
}

void loop()
{
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(100);
  Serial.println(analogRead(lightPin)); //Write the value of the photoresistor to the serial monitor.
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(100);
  Serial.println(analogRead(lightPin)); //Write the value of the photoresistor to the serial monitor.
  delay(1000);               // wait for a second
 }

_______________________________________________________________________

2. Mega 2560 And PCF8591 (Digital To Analog)

Diagram:
Code:
#include "Wire.h"
#define PCF8591 (0x90 >> 1) 

int Ain = 0;

int RawValue0 = 0;
int DACout = 0;

float DACoutVolt = 0.0;
float Voltage = 0.0;

void setup()
{
  Wire.begin();
  Serial.begin(9600);
}
void loop()
{
  for (int i = 0; i < 256; i++)
  {
    Wire.beginTransmission(PCF8591); 
    Wire.write(0x40); // sets the PCF8591 into a DA mode
    Wire.write(i); // sets the outputn
    Wire.endTransmission();     
    
    delay(500);    
    
    DACout = i;
    RawValue0 = analogRead(Ain);
    Voltage = (RawValue0 * 5.0 ) / 1024.0;
    DACoutVolt = (DACout * 5.0)/256.0;
    Serial.print("DAC Out = ");
    Serial.print(DACout);
    Serial.print("\tDAC Target Voltage = ");
    Serial.print(DACoutVolt, 3);
    Serial.print("\tRaw ADC Value = ");
    Serial.print(RawValue0);
    Serial.print("\tVoltage = ");
    Serial.println(Voltage, 3);
  }
}

_______________________________________________________________________

3. Mega 2560 And PCF8574 Bus

Diagram:
Code:
#include <Wire.h>

#define PCF8574_I2C_ADDR 0x20

#define P0 0
#define P1 1
#define P2 2
#define P3 3
#define P4 4
#define P5 5
#define P6 6
#define P7 7

void setup() {
  Wire.begin();        // initialize the I2C/TWI interface
}

void loop() {
  // send the data to the LEDs
  turnPinLowOnPCF8574P(PCF8574_I2C_ADDR, P4);
  delay(300);
  turnPinLowOnPCF8574P(PCF8574_I2C_ADDR, P5);
  delay(300);
  turnPinLowOnPCF8574P(PCF8574_I2C_ADDR, P6);
  delay(300);
  turnPinLowOnPCF8574P(PCF8574_I2C_ADDR, P7);
  delay(300);
  turnPinLowOnPCF8574P(PCF8574_I2C_ADDR, P6);
  delay(300);
  turnPinLowOnPCF8574P(PCF8574_I2C_ADDR, P5);
  delay(300);  
}

void turnPinLowOnPCF8574P(int chipI2CAddress, int pinNumber) {
  Wire.beginTransmission(chipI2CAddress);
  Wire.write(~(1 << pinNumber));
  Wire.endTransmission();
}


_______________________________________________________________________

4. Mega 2560: Infrarred Receiver + TV Remote





Diagram
Code
#include <IRremote.h>
int redledState = LOW;
int greenledState = LOW;
int fanState = LOW;
int fanPin = 10;
int irpin = 8;
IRrecv irIN(irpin);
decode_results results;
void setup()
{
  Serial.begin(9600);
  pinMode(10,OUTPUT);
  irIN.enableIRIn();
}
void loop()
{
  if(irIN.decode(&results))
  {
    Serial.println(results.value, HEX);
    irIN.resume();
  }


  if(results.value == 0xFEAC02E5)//this value was given back from the IR receiver and represents a key on the remote.//
  {
   fanState = !fanState;
   digitalWrite(fanPin, fanState);
   delay(15);
  }
}

_______________________________________________________________________

5. RF Communication With Mega 2560 And Arduino UNO


Diagrams:




Codes:


Sender:

#include <VirtualWire.h>

void setup()
{
    Serial.begin(9600);    
    Serial.println("Tx RF");

    // Se inicializa el RF
    vw_setup(2000); // velocidad: Bits per segundo
    vw_set_tx_pin(2); //Pin 2 como salida para el RF 
}

void loop()
{

    
    while (Serial.available() > 0) 
    {
      char dato[1];
      dato[0] = Serial.read();
      //Enviamos el carácter recibido al RF
      vw_send((uint8_t*)dato,sizeof(dato));
      vw_wait_tx();         
    }
    delay(200);
}


Receiver:

#include <VirtualWire.h>

void setup()
{
    Serial.begin(9600);  // Debugging only
    Serial.println("setup");

    // Se inicializa el RF
    vw_setup(2000);  // velocidad: Bits per segundo
    vw_set_rx_pin(2);  //Pin 2 como entrada del RF
    vw_rx_start();       // Se inicia como receptor
    
    pinMode(13, OUTPUT);    //Configuramos el pin del Led como entrada
    digitalWrite(13, false);
}

void loop()
{
    uint8_t dato;
    uint8_t datoleng=1;
    //verificamos si hay un dato valido en el RF
    if (vw_get_message(&dato,&datoleng))
    {
        if((char)dato=='y')
        {
            digitalWrite(13, true); //Encendemos el Led
        }
        else if((char)dato=='z')
        {
            digitalWrite(13, false); //Apagamos el Led
        }            
    }
} 
 
_______________________________________________________________________

6. Serial Communication With Mega 2560 And Arduino UNO

Diagram:
Codes:

Sender:

// Sender Information
unsigned char START_BYTE = 0x53; // ASCII "S"
unsigned char counterValue = 0;
unsigned char staticValue = 5;
unsigned char checksum = 0;
 
void setup() {
  Serial.begin(9600);
}
 
void loop() {
  
  // Increment our counter
  counterValue = counterValue + 1;
  
  // Check for overflow, and loop
  if (counterValue > 250)
    counterValue = 0;
    
  // Calculate our checksum
  checksum = counterValue + staticValue;
  
  // Important: Serial.write must be used, not print
  Serial.write(START_BYTE);
  Serial.write(counterValue);
  Serial.write(staticValue);
  Serial.write(checksum);
  
  // We only need to send a packet every 250 ms. 
  // If your code starts to get complicated, 
  // consider using a timer instead of a delay
  delay(250); 

Receiver:

// Sender Information
unsigned char START_BYTE = 0x53; // ASCII "S"
unsigned char counterValue = 0;
unsigned char staticValue = 0;
unsigned char checksum = 0;
 
// Sync Byte flag
boolean syncByteFound = 0;
 
void setup() {
  Serial.begin(9600);
  Serial1.begin(9600);
}
 
void loop() {
  
  unsigned char rxByte = 0;
  unsigned char calculatedChecksum = 0;
  
  // Check to see if there's something to read
  if (Serial1.available() > 0 ) {
    
    // If we're waiting for a new packet, check for the sync byte
    if (syncByteFound == 0) {
      rxByte = Serial1.read();
      if (rxByte == 0x53)
        syncByteFound = 1;
    }
    
    // If we've found our sync byte, check for expected number of bytes
    if (Serial1.available() > 2) {
      counterValue = Serial1.read();
      staticValue = Serial1.read();
      checksum = Serial1.read();
        
      calculatedChecksum =  counterValue + staticValue;
      
      // Print out our serial information to debug
      Serial.print("["); Serial.print("S"); Serial.print("]");
      Serial.print("["); Serial.print(counterValue); Serial.print("]");
      Serial.print("["); Serial.print(staticValue); Serial.print("]");
      Serial.print("["); Serial.print(checksum); Serial.print("]");
      
      if (calculatedChecksum == checksum) 
        Serial.println("[Checksum Passed]");


      else
        Serial.println("[Checksum FAILED]");
            
      syncByteFound = 0;
    }
  }
}


_______________________________________________________________________

7. Projects With Arduino UNO

http://guillengap.blogspot.com/2016/07/ebook-projects-with-arduino-uno.html


https://www.amazon.com/dp/B01EZO7DBA

https://www.amazon.com/Guillermo%20Perez/e/B01EZOTUVQ/

guillengap@gmail.com

domingo, 14 de mayo de 2017

MATLAB Tutorial

1. IMAGE PROCESSING USING WIENER FILTER

The Wiener filter can be used to filter out the noise from the corrupted signal to provide an estimate of the underlying signal of interest. The Wiener filter is based on a statistical approach, and a more statistical account of the theory is given in the minimum mean square error (MMSE) estimator article.

The download code of the Image Processing Using Wiener Filter, you can get it in the following link: Image Processing Using Wiener Filter
_______________________________________________________________________

2. AUDIO SIGNAL PROCESSING USING FDATOOL 


The audio must be in wav format and if you don`t have it, then you can make it through many programs available on the Internet.

By fdatool, we can design high-pass or lowpass or bandpass filters. Also, digital filters may be IIR or FIR; In my case I`m designing a highpass filter and I`m trying to eliminate the deep voice.

In this example we will make a high pass filter. The steps are the following:
put the command > fdatool



When the window opens, we write the following information:
Highpass filter
Type IIR - Elliptic
Fs = 8000 Hz
Fstop = 1500 Hz
Fpass = 2000 Hz
Rs = 60 dB
Rp = 1 dB

Click on Design Filter



Fdatool Window




Right-click on:
Structure> Current filter information> convert to single section
Then select:
File> Export ...
We give a name to the numerator and denominator of the filter.

Finally click on Export and save the project.


Code:


In the Matlab code we have to put the audio path that we will process and the name of the audio that we will create. When we run the code we will have audio signal processed in the same folder as the original audio signal.


[xt,Fs]=wavread('d:\Audio.wav');
yt=filter(NumHp,DenHp,xt);
soundsc(xt);
pause(2);
soundsc(yt);
fvtool(xt);
fvtool(yt);
%salvar audio filtrado
wavwrite(yt,'Audio01.wav'
_______________________________________________________________________

3. FOURIER TRANSFORM FUNCTIONS


The download code of the Fourier Transform Functions, you can get it in the following link: Fourier Transform Functions
_______________________________________________________________________

4. BANDPASS RLC CIRCUIT

The download code of the Fourier Transform Functions, you can get it in the following link:
Bandpass RLC Network

_______________________________________________________________________

5.  PLOTTING RIEMANN Z FUNCTION

Commands:

plotfunc2d(abs(zeta(1/2 + y*I)), y = 0..30, Mesh = 500)

plotfunc2d(abs(zeta(1/2 + y*I)), y = 0..30, Mesh = 500, AxesTitles = ["y", "zeta"])

plotfunc2d(abs(zeta(1/2 + y*I)), y = 0..50, Mesh = 500, AxesTitles = ["y", "zeta"])

fplot (abs(zeta(1/2+y*I)),[0..30])

zeta(-2)

zeta(0)

zeta(2)

zeta(1 + I, 1)

zeta(0,1)

zeta(infinity,1)

zeta(0.5 + 14.13472514*I, 2)

numeric::solve(zeta(1/2 + I*y), y = 10..20)

numeric::solve(zeta(1/2 + I*y), y = 10..22)

numeric::solve(zeta(1/2 + I*y), y = 20..26)

_______________________________________________________________________

6.  IDENTIFICATION OF FACES



http://guillengap.blogspot.com/2017/05/ebook-identification-of-faces-with.html

 https://www.amazon.com/dp/B071ZKG37Q
 
https://www.amazon.com/Guillermo%20Perez/e/B01EZOTUVQ/

guillengap@gmail.com

ATtiny85 Tutorial

1. FLASH LED


Download: Flash LED
_______________________________________________________________________

2. PUSH BUTTON



Download: Push Button
_______________________________________________________________________

3. FLASHING THERMOMETER




#include <avr/sleep.h>                                                                                                                                                                                                                                                                                                                                                                             

const int red = 0;                         // PB0
const int green = 2;                       // PB2

int ReadADC() {
  ADCSRA = ADCSRA | 1<<ADEN;               // Enable ADC
  set_sleep_mode(SLEEP_MODE_ADC);
  sleep_enable();
  sleep_cpu();                             // Go into ADC noise reduction mode
  int low, high;                           // Return here on ADC interrupt
  low = ADCL;
  high = ADCH;
  ADCSRA = ADCSRA & ~(1<<ADEN);            // Disable ADC to save power
  return (high<>i & 1;
    if (show || b || (i==0)) {
      if (value>>i & 1) colour = red; else colour = green;
      digitalWrite(colour, HIGH);
      WDDelay(0);                              // 12msec flash
      digitalWrite(colour, LOW);
      WDDelay(6);                              // 1 second gap
      show = true;
    }
    i--;
  } while (i>=0);
}

// Watchdog timer **********************************************

// Use Watchdog for time delay; n=0 is 16ms; n=6 is 1sec ; n=9 is 8secs, 
void WDDelay(int n) {
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  WDTCR = 1<<WDIE | (n & 0x8)<<2 | 1<<WDE | (n & 0x7);
  sleep_enable();
  sleep_cpu();
}

ISR(WDT_vect) {
  // Special sequence to disable watchdog timer
  WDTCR = 1<<WDCE | 1<<WDE;
  WDTCR = 0;
}

// Setup and main loop **********************************************

void setup() {
  // Turn off Timer/Counter0, Timer/Counter1, and USI to save power
  PRR = 1<<PRTIM1 | 1<<PRTIM0 | 1<<PRUSI;
  // Define inputs and outputs
  pinMode(red, OUTPUT);
  pinMode(green, OUTPUT);
  digitalWrite(red, LOW);
  digitalWrite(green, LOW);
  // Set up ADC for temperature
  ADMUX = 0<<REFS2 | 2<<REFS0 | 15<<MUX0;  // temperature and 1.1V reference
  ADCSRA = 1<<ADEN | 1<<ADIE | 3<<ADPS0;   // enable ADC, interrupt, 125kHz ADC clock
}

void loop() {
  int Temperature;
  // Go to sleep to save power until the watchdog timer wakes us up
  WDDelay(9);                              // 8 second delay
  WDDelay(9);                              // and another 8 second delay
  Temperature = (ReadADC()*31 - 8837)/33;  // In degrees Celsius
  Flash(NegaBinary(Temperature));
}


Download: Flashing Thermmeter
_______________________________________________________________________

4. TWO PWM





Download: Two PWM
_______________________________________________________________________ 

5. WAVEFORM GENERATOR







SQUARE WAVE


SAWTOOTH WAVE


TRIANGLE WAVE

_______________________________________________________________________ 

6. DIGITAL MUSIC





int Scale[] = { 
  680,  721,  764,  809,  857,  908,  962, 1020, 1080, 1144, 1212, 1284, 
 1361, 1442, 1528, 1618, 1715, 1817, 1925, 2039, 2160, 2289, 2425, 2569,
 2722, 2884, 3055, 3237, 3429, 3633, 3849, 4078 };
 
const int Channels = 4;
const int Tempo = 4;      // 4 = 4 beats per second
const int Decay = 9;      // Length of note decay; max 10

volatile unsigned int Acc[Channels];
volatile unsigned int Freq[Channels];
volatile unsigned int Amp[Channels];

// Play Happy Birthday

const uint32_t Tune[] PROGMEM = {
//_*_*__*_*_*__*_*__*_*_*__*_*__*_
//C D EF G A BC D EF G A BC D EF G
0b00000000000000000100000000000000,
0b00000000000000000001000000000000,

0b10000000000000000000010000000000,
0b00000000000100000000000000000000,
0b00001001000000000001000000000000,
0b00000000000000000000000000000000,
0b00000000000000000000000010000000,
0b00000000000000000000000000000000,

0b00100000000000000000000100000000,
0b00000000000000000000000000000000,
0b00000101000000000000000000000000,
0b00000000000010000000000000000000,
0b00000000000000000001000000000000,
0b00000000000000000001000000000000,

0b10000000000000000000010000000000,
0b00000000000000000000000000000000,
0b00000101000000000001000000000000,
0b00000000000001000000000000000000,
0b00000000000000000000000000100000,
0b00000000000000001000000000000000,

0b10000000000000000000000010000000,
0b00000000000000000000000000000000,
0b00001001000000000000000000000000,
0b00000000000000000000000000000000,
0b00000000000000000001000000000000,
0b00000000000000000001000000000000,

0b10000000000000000000000000000001,
0b00000000000000000100000000000000,
0b00100000000000000000000000001000,
0b00000000000000000000000000000000,
0b00001000000000000000000010000000,
0b00000000000000000010000000000000,

0b00000100000000000000000100000000,
0b00000000000000000000000000000000,
0b00000000000000000000010000000000,
0b00000000000000000001000000000000,
0b00000000000000000000000000000100,
0b00000000000000000000000000000100,

0b00000001000000000000000000001000,
0b00000000000000000000000000000000,
0b00000000000000000000000010000000,
0b00000000000010000000000000000000,
0b00000101000000000000000000100000,
0b00000000010000000000000000000000,

0b10001001000000000000000010000000,
0xFF}; // End of tune

//Globals persist throughout tune
int TunePtr = 0, Chan = 0;

// Watchdog interrupt plays notes
ISR(WDT_vect) {
  sei();   // Allow interrupts
  WDTCR |= 1<<WDIE;
  unsigned long Chord = pgm_read_dword(&Tune[TunePtr]);
  if (Chord == 0xFF) return;
  TunePtr++;
  // Read the bits in Chord
  for (int Note = 0; Note < 32; Note++) {
    if ((Chord & 0x80000000) != 0) {
      Freq[Chan] = Scale[Note];
      Amp[Chan] = 1<<(Decay+5);
      Chan = (Chan + 1) % Channels;
    }
    Chord = Chord<<1;
  }
}

// Generate square waves on 4 channels
ISR(TIMER0_COMPA_vect) {
  signed char Temp, Mask, Env, Note, Sum=0;
  for (int c = 0; c < Channels; c++) {
    Acc[c] = Acc[c] + Freq[c];  
    Amp[c] = Amp[c] - (Amp[c] != 0);
    Temp = Acc[c] >> 8;
    Mask = Temp >> 7;
    Env = Amp[c] >> Decay;
    Note = (Env ^ Mask) + (Mask & 1);
    Sum = Sum + Note;
  }
  OCR1B = Sum + 128;
}

void setup() {
  // Enable 64 MHz PLL and use as source for Timer1
  PLLCSR = 1<<PCKE | 1<<PLLE;     

  // Set up Timer/Counter1 for PWM output
  TIMSK = 0;                     // Timer interrupts OFF
  TCCR1 = 1<<CS10;               // 1:1 prescale
  GTCCR = 1<<PWM1B | 2<<COM1B0;  // PWM B, clear on match

  OCR1B = 128;
  DDRB = 1<<DDB4;                // Enable PWM output on pin 4

  // Set up Timer/Counter0 for 20kHz interrupt to output samples.
  TCCR0A = 3<<WGM00;             // Fast PWM
  TCCR0B = 1<<WGM02 | 2<<CS00;   // 1/8 prescale
  OCR0A = 99;                    // Divide by 100
  TIMSK = 1<<OCIE0A;             // Enable compare match, disable overflow
 
  // Set up Watchdog timer for 4 Hz interrupt for note output.
  WDTCR = 1<<WDIE | Tempo<<WDP0; // 4 Hz interrupt
}

void loop() {
}

Download: Digital Music
 
https://www.amazon.com/Guillermo%20Perez/e/B01EZOTUVQ/

guillengap@gmail.com