Forum Replies Created
-
AuthorPosts
-
Jason JordonParticipant
Hi Tony,
Atmega 8 can be used for applications that are a lot better than a line follower. That is why the scope for development boards (which Soubhik) exists. For instance, here is a R/C based robot: http://letsmakerobots.com/node/27952
Soubhik, I will soon give you a solution.
Jason JordonParticipantI found a pdf, the link is getting marked into spam so I am sticking the text here, tell me if you want more info, I will email the link.
1 Introduction
This application note describes how to set up and use the SPI module in the AVR®
XMEGA. Both interrupt controlled and polled C code drivers and examples are
included for master and slave applications.
Serial buses are more and more preferred over parallel. The wiring is simpler, and
as the efficiency of serial interfaces increases, the speed advantage of a parallel
transmission gets less important. Typical peripherals that use a serial interface are
converters (A/D and D/A), memories (RAM and EEPROM), real time clocks,
sensors and other controllers for LCD, CAN USB etc.
Figure 1-1. Basic SPI implementation
MASTER SLAVE
SCK
MOSI
SS
MISO
8-bit
Microcontrollers
Application Note
Rev. 8057A-AVR-02/08 2 AVR1309
8057A-AVR-02/08
2 The SPI bus
The Serial Peripheral Interface (SPI) is mainly used in synchronous serial
transmissions in a master/slave relationship. The master initiates and controls the
transfer, while the slave responds.
SPI is a full duplex interface, and at a low cost enabling high-speed communication
between master and slave. SPI does not have a specific higher-level protocol, which
means there is almost no overhead. The drawback is that there is no
acknowledgement and flow control, and the master doesn’t even have to be aware of
the slave’s presence.
2.1 Data and control lines
The standard SPI configuration makes use of two control and two data lines. The data
lines are MOSI (Master Out, Slave In) and MISO (Master In, Slave Out), transferring
data in each direction. The control lines are SCK (SPI Clock) and SS (Slave Select). If
SS is used, the master selects a slave device by pulling this line low, and supplies the
clock signal. Data is now transferred in both directions simultaneously, and it is up to
a higher-level protocol to define the meaning of each byte.
Figure 2-1. Master/slave interconnection
MASTER SLAVE
8 BIT SHIFT REGISTER
MSB LSB
SPI CLOCK GENERATOR
8 BIT SHIFT REGISTER
MSB LSB
MISO MISO
MOSI MOSI
SCK SCK
SHIFT
ENABLE
SS SS
GPIO
If multiple slaves exists and should be independently addressed, the master must
generate a SS signal for each slave. This is illustrated in Figure 2-2. AVR1309
3
8057A-AVR-02/08
Figure 2-2. Multi slave implementation
SCK
MOSI
MISO
MASTER
SS1
SS2
SS3
SCK
MOSI
SLAVE #1
MISO
SS
SCK
MOSI
SLAVE #2
MISO
SS
SCK
MOSI
SLAVE #3
MISO
SS
2.2 Modes and configuration
There is no official specification for SPI communication, making flexibility of the
devices important. Clock polarity (CPOL) and clock phase (CPHA) determines the
data setup and sampling point, and must be configured the same for devices to
communicate.
Table 2-1. SPI modes
Configuration
SPI mode
CPOL CPHA
Leading edge Trailing edge
0 0 0 Rising Sample Falling Setup
1 0 1 Rising Setup Falling Sample
2 1 0 Falling Sample Rising Setup
3 1 1 Falling Setup Rising Sample
For more information about SPI modes and configuration, please see the XMEGA
SPI data sheet. 4 AVR1309
8057A-AVR-02/08
3 The XMEGA SPI module
The XMEGA SPI module is designed for high-speed data transfers between the
XMEGA and other SPI devices. The control bits allow flexible configuration to enable
a flawless connection.
3.1 Registers
The SPI module consists of the baud rate generator, status and control logic with
supporting registers listed in Table 3-1.
Table 3-1. SPI module registers.
Register name C struct and element
SPI Control Register SPIx.CTRL
SPI Interrupt Control Register SPIx.INTCTRL
SPI Status Register SPIx.STATUS
SPI Data Register SPIx.DATA
All control bits with exception of the interrupt level bits, are located in CTRL. The two
interrupt level bits are found in INTCTRL, and the SPI interrupt and write collision
flags in STATUS.
The DATA register is a read/write register for data transfers. Reading the registers
returns the data currently in the SPI shift register, while writing will initiate a data
transmission. The system is single buffered in the transmit direction and double
buffered in the receive direction. As a result, new data must not be written to the
DATA register before the entire shift cycle is complete. To avoid losing data, a
received character must be read from DATA before the next character has been
completely shifted in.
3.2 The SS pin
In master mode the SS pin is fully configurable from software, and typically used as
one of these three options:
• Input (interrupt) from other master(s) accessing the bus
• Output SS signal to slave
• General output
If the SPI module’s SS pin is configured as input, the function is like the first option
above. This SS input function is controlled from the SPI module hardware, and the SS
pin must be held logic high to ensure master SPI operation. If pulled low by other
master(s) using the SPI bus, the SPI module will avoid bus contention by entering
slave mode and consequently not driving the SCK and MOSI lines. Entering slave
mode is signaled by setting the SPI interrupt flag, generating an interrupt if enabled.
Configuring the SS pin as output enables the two last typical options, both controlled
from software and not affecting the SPI module operation. The SS pin is no different
than any other GPIO pins when it is configured as an output.
Often, several slaves are connected to the same bus, while the application would
address one slave at a time. As illustrated in Figure 2-2, this can be done using AVR1309
5
8057A-AVR-02/08
several GPIO pins, one for each slave or through some external logic reducing the
number of pins needed.
4 SPI driver
The driver included in this application note supports both polled and interruptcontrolled SPI operation for both master and slave. The driver is intended for rapid
prototyping and to get started with the XMEGA SPI module.
4.1 Files
The SPI driver source code consists of the following files:
• spi_driver.c – driver source file
• spi_driver.h – driver header file
For a complete overview of the available driver interface functions and their use,
please refer to the source code documentation.
5 Code examples
Two code examples are included that show how to use the SPI drivers for interruptdriven and polled operation. In both examples, SPIC is used as master, while SPID
serves as slave.
5.1 Files
The SPI code examples are contained in the following files:
• spi_interrupt_example.c – Example of interrupt-driven SPI operation
• spi_polled_example.c – Example of polled SPI operation
5.2 Interrupt-driven
The interrupt-driven code example uses the SPI driver to instantiate a master and a
slave. A data packet is then initialized and sent to the slave. When data is received at
the slave, an ISR increments the data before it is put back in the data register, ready
to be shifted back to the master. The master interrupt handler will transfer the number
of bytes contained in the data packet. When the complete flag for the data packet is
set, the master verifies that it has received the correct values.
5.3 Polled
The polled code example uses the SPI driver to instantiate a master and slave. The
example is split into two sections:
First, the master sends one byte at the time to the slave, the slave increments the
byte and puts it in the shift register. The master sends a dummy byte, in order to fetch
the byte from the slave. The master then verifies that it has received the correct
value.
In the second section, a data packet is initialized and sent to the slave. The slave
does not manipulate the data, which is shifted back to the slave as new bytes are 6 AVR1309
8057A-AVR-02/08
transferred. When the whole packet is sent, the master verifies that the received
bytes match the sent bytes (except for the last byte which is not shifted back to the
master).Jason JordonParticipantOk, under wired I2C SPI protocols would suffice while under wireless zigbee etc would do, right?
Jason JordonParticipantusing a mobile phone would be better as it would make the working pretty easy. You need to have a GSM receiver module and in the code, you can even enter a number to which the system would reply everytime after it is calibrated.
Jason JordonParticipanttell me if this one works (made on turbo c)
/* Defines required for serial i/o */
#define COM_PORT 1 /* Serial device connected to COM 1 */
#define SPEED 4800 /* baud rate = 4800 */
#define CR 0x0d
#define LF 0x0a
#define ESC 0x1b
#define BEEP 0x07
/* Some helpful defines */
#define SPACE 0x20
#define COMMA 0x2C
#define MAXSIZE 100 /* GPS at most, sends 80 or so chars per message string. So set maximum to 100 */
#include < stdio.h >
#include < ctype.h > /* required for the isalnum function */
#include < stdlib.h >
#include < string.h >
#include < conio.h >
#include < math.h >
#include < dos.h >
#include "ibmcom3.h" /* for serial */
/* Prototypes */
void comm_setting(void); /* Set com port */
void close_com(void); /* Close com port */
int main(void) {
unsigned char charRead; /* char read from COM port */
unsigned char stringRead[MAXSIZE]; /* Buffer collects chars read from GPS */
unsigned char tempString[MAXSIZE];
unsigned char timeString[12];
unsigned char latitudeString[11];
unsigned char latitudeCardinalString[3];
unsigned char longitudeString[12];
unsigned char longitudeCardinalString[3];
unsigned char *pChar;
unsigned char dummyChar;
unsigned long utcTime, estTime; /* Coordinated Universal Time and Eastern Standard Time */
unsigned long utcHour, estHour;
unsigned long utcMinutes, estMinutes;
unsigned long utcSeconds, estSeconds;
unsigned char lastCommaPosition;
float latitude;
int latDegrees;
float latMinutes;
float longitude;
int longDegrees;
float longMinutes;
FILE *gpsFile; /* Text file of GPS strings read */
unsigned int j, k; /* dummy variable */
unsigned int i; /* Number of chars read per GPS message string */
unsigned int numLinesRead; /* Number of GPS strings read */
dummyChar = 'A'; pChar = &dummyChar;
gpsFile = fopen("gpsData.txt", "w");
printf("Initializing port...");
comm_setting();
printf("done/n");
numLinesRead = 0;
printf("Entering while loop.../n");
do {
charRead = com_rx(); /* read char from serial port */
if(charRead == '$') { /* GPS messages start with $ char */
i = 0;
numLinesRead++;
stringRead = charRead;
do {
charRead = com_rx();
if( (charRead != '/0') && (isalnum(charRead) || isspace(charRead) || ispunct(charRead)) ) {
i++;
stringRead = charRead;
}
} while(charRead != CR);
/* By this point, a complete GPS string has been read so save it to file */
/* Append the null terminator to the string read */
stringRead[i+1] = ' ';
/* Analyze string that we collected */
j = 0;
pChar = stringRead;
while(*(pChar+j) != COMMA) {
tempString[j] = *(pChar+j);
j++;
}
tempString[j] = ' ';
/* Check if string we collected is the $GPGGA message */
if(tempString[3] == 'G' && tempString[4] == 'G' && tempString[5] == 'A') {
/*
Found GPGGA string. It has 14 commas total. Its NMEA sentence structure is:
$GPGAA,hhmmss.ss,ddmm.mmmm,n,dddmm.mmmm,e,q,ss,y.y,a.a,z,g.g,z,t.t,iii*CC
| | | | | | | | | | | | | | |
0 1 2 3 4 5 6 7
0123456789012345678901234567890123456789012345678901234567890123456789012
where:
GPGAA : GPS fixed data identifier
hhmmss.ss : Coordinated Universal Time (UTC), also known as GMT
ddmm.mmmm,n : Latitude in degrees, minutes and cardinal sign
dddmm.mmmm,e : Longitude in degrees, minutes and cardinal sign
q : Quality of fix. 1 = there is a fix
ss : Number of satellites being used
y.y : Horizontal dilution of precision
a.a,M : GPS antenna altitude in meters
g.g,M : geoidal separation in meters
t.t : Age of the defferential correction data
iiii : Deferential station's ID
*CC : checksum for the sentence
*/
pChar = stringRead;
/* Get UTC time */
j = 7; /* start of time field */
k = 0;
while(*(pChar+j) != COMMA) {
timeString[k] = *(pChar+j);
j++;
k++;
}
lastCommaPosition = j;
timeString[k] = ' ';
sscanf(timeString, "%ld", &utcTime);
utcHour = (utcTime/10000); /* extract Hours from long */
utcMinutes = (utcTime - (utcHour*10000))/100; /* extract minutes from long */
utcSeconds = utcTime - (utcHour*10000) - (utcMinutes*100); /* extract seconds from long */
if(utcHour >= 4 && utcHour <= 23) estHour = utcHour - 4;
else estHour = utcHour + 20;
estMinutes = utcMinutes;
estSeconds = utcSeconds;
/* NB: %02ld formats long to print 2 chars wide, padding with 0 if necessary */
printf("%02ld:%02ld:%02ld UTC = %02ld:%02ld:%02ld EST", utcHour, utcMinutes, utcSeconds, estHour, estMinutes, estSeconds);
/* Get lattitude: ddmm.mmmm */
pChar = stringRead;
j = lastCommaPosition + 1;
k = 0;
while(*(pChar+j) != COMMA) {
latitudeString[k] = *(pChar+j);
j++;
k++;
}
lastCommaPosition = j;
latitudeString[k] = ' ';
sscanf(latitudeString, "%f", &latitude);
latDegrees = (int)(latitude/100);
latMinutes = (float)(latitude - latDegrees*100);
printf("/t%02d DEG/t%2.4f MIN", latDegrees, latMinutes);
/* Get lattitude Cardinal direction */
pChar = stringRead;
j = lastCommaPosition + 1;
k = 0;
while(*(pChar+j) != COMMA) {
latitudeCardinalString[k] = *(pChar+j);
j++;
k++;
}
lastCommaPosition = j;
latitudeCardinalString[k] = ' ';
printf(" %s", latitudeCardinalString);
/* Get longitude: dddmm.mmmm */
pChar = stringRead;
j = lastCommaPosition + 1;
k = 0;
while(*(pChar+j) != COMMA) {
longitudeString[k] = *(pChar+j);
j++;
k++;
}
lastCommaPosition = j;
longitudeString[k] = ' ';
sscanf(longitudeString, "%f", &longitude);
longDegrees = (int)(longitude/100);
longMinutes = (float)(longitude - longDegrees*100);
printf("/t%03d DEG/t%2.4f MIN", longDegrees, longMinutes);
printf("/n");
} /* else not a GPGGA sentence */
fprintf(gpsFile, "%d: (%d) %s/n", numLinesRead, i, stringRead);
} /* otherwise not a $ character... so loop back until one arrives */
} while(!kbhit());
printf("Exiting...");
close_com(); /* Finished with serial port so close it */
fclose(gpsFile);
printf("done/n");
return (0);
} /* end of main */
void comm_setting(void) {
int dummy;
dummy = com_install(COM_PORT);
if(dummy != 0) {
switch (dummy) {
case 1 : printf("Invaid port number/n");
break;
case 2 : printf("No UART fot specified port/n");
break;
case 3 : printf("Drivers already installed/n");
break;
default : printf("Err #%d/n", dummy);
break;
}
exit(1);
} com_raise_dtr();
com_set_speed(SPEED);
com_set_parity(COM_NONE, STOP_BIT_1);
}
void close_com(void) {
com_lower_dtr();
com_deinstall();
}Jason JordonParticipantThanks Tobin for such a precise answer.
Jason JordonParticipantyes, PIC is advanced microcontroller and all PIC can be programmed using C.
Jason JordonParticipantwhat type of LCD are you using for the board? 16X2?? Is it 8051 based?
Jason JordonParticipantyes,
if the connections of your circuit are correct, then it is the USBasp which is the bugger here.
Jason JordonParticipantI found this code:
#include <avr/io.h> // include I/O definitions (port names, pin names, etc)#include “global.h” // include our global settings////
Defines
#define BV(bit) (1<<(bit)) // Byte Value => converts bit into a byte value. One at bit location.#define cbi(reg, bit) reg &= ~(BV(bit)) // Clears the corresponding bit in register reg#define sbi(reg, bit) reg |= (BV(bit)) // Sets the corresponding bit in register reg////
Function Prototypes
void adc_init(void); // Will set up the registers for A/D conversion//
Begin Code
int main(void){unsigned short adc_result; // Just a variable to hold the resultadc_init(); // Call the init functionDDRF = 0x00; // configure a2d port (PORTF) as input so we can receive analog signalsPORTF = 0x00; // make sure pull-up resistors are turned off (else we’ll just read 0xCFF)while(1){sbi(ADCSRA,ADSC); // start a conversion by writing a one to the ADSC bit (bit 6)while(ADCSRA & 0b01000000); // wait for conversion to complete (bit 6 will change to 0)adc_result = ((ADCL) | ((ADCH)<<); // 10-bit conversion for channel 0 (PF0)}return 0;} // end main()//void adc_init(void){sbi(ADCSRA,ADEN); // enables ADC by setting bit 7 (ADEN) in the ADCSRAcbi(ADCSRA,ADFR); // single sample conversion by clearing bit 5 (ADFR) in the ADCSRAADCSRA = ((ADCSRA & 0b11111000) | 0b00000110); // selects div by 64 clock prescalerADMUX = ((ADMUX & 0b00111111) | 0b01000000); // selects AVCC as Vrefcbi(ADMUX,ADLAR); // selects right adjust of ADC resultADMUX &= 0b11100000; // selects single-ended conversion on PF0}Jason JordonParticipantYou can use a MQ-3 Alcohol sensor that works at 5V DC and can easily be interfaced with microcontroller
Jason JordonParticipantyou haven’t interfaced any LCD to the circuit??
Jason JordonParticipantHi,
Prescalar is a circuit that scales up (multiplies) or scales down (divides) an input signal before it is processed. I will post the code/logic soon.
April 11, 2013 at 10:24 am in reply to: how to transmit analogue signals using infrared and display output as decimal??? #9462Jason JordonParticipantI sense it to be a simple analog to digital conversion circuit. You will need an ADC here. Tell me what microcontroller are you using here. There are some ADC programs in the Labs (8051-AVR and PIC) section.
April 11, 2013 at 10:22 am in reply to: Bipolar Stepper Motor 8051 C-program is needed!!! Please share if anybody have one. #9461Jason JordonParticipantHi,
I am very sure that there are some C-based bipolar stepper motor programs in the “contribution” section. Find them out!!!
-
AuthorPosts