I am trying to follow a tutorial from youtube on using ROS with Arduino to control motors, and I have connected my L298N with the battery precisely as the video describes and have uploaded sketch 1 with the supporting folder and it loads properly. The Arduino is powered properly via USB, but that connection is not shown in the diagram. When I type the "e" command, I get the proper response of "0 0" and when I do the "o 255 255" it says "OK" and drives properly but upon using "e" to recheck the encoders I am getting the same "0 0". If anyone can spot something wrong with this, I would really appreciate the help in fixing it. Diagram and Code Below
Code:
#define USE_BASE // Enable the base controller code
//#undef USE_BASE // Disable the base controller code
/* Define the motor controller and encoder library you are using */
#ifdef USE_BASE
/* The Pololu VNH5019 dual motor driver shield */
//#define POLOLU_VNH5019
/* The Pololu MC33926 dual motor driver shield */
//#define POLOLU_MC33926
/* The RoboGaia encoder shield */
//#define ROBOGAIA
/* Encoders directly attached to Arduino board */
#define ARDUINO_ENC_COUNTER
/* L298 Motor driver*/
#define L298_MOTOR_DRIVER
#endif
//#define USE_SERVOS // Enable use of PWM servos as defined in servos.h
#undef USE_SERVOS // Disable use of PWM servos
/* Serial port baud rate */
#define BAUDRATE 57600
/* Maximum PWM signal */
#define MAX_PWM 255
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
/* Include definition of serial commands */
#include "commands.h"
/* Sensor functions */
#include "sensors.h"
/* Include servo support if required */
#ifdef USE_SERVOS
#include <Servo.h>
#include "servos.h"
#endif
#ifdef USE_BASE
/* Motor driver function definitions */
#include "motor_driver.h"
/* Encoder driver function definitions */
#include "encoder_driver.h"
/* PID parameters and functions */
#include "diff_controller.h"
/* Run the PID loop at 30 times per second */
#define PID_RATE 30 // Hz
/* Convert the rate into an interval */
const int PID_INTERVAL = 1000 / PID_RATE;
/* Track the next time we make a PID calculation */
unsigned long nextPID = PID_INTERVAL;
/* Stop the robot if it hasn't received a movement command
in this number of milliseconds */
#define AUTO_STOP_INTERVAL 2000
long lastMotorCommand = AUTO_STOP_INTERVAL;
#endif
/* Variable initialization */
// A pair of varibles to help parse serial commands (thanks Fergs)
int arg = 0;
int index = 0;
// Variable to hold an input character
char chr;
// Variable to hold the current single-character command
char cmd;
// Character arrays to hold the first and second arguments
char argv1[16];
char argv2[16];
// The arguments converted to integers
long arg1;
long arg2;
/* Clear the current command parameters */
void resetCommand() {
cmd = NULL;
memset(argv1, 0, sizeof(argv1));
memset(argv2, 0, sizeof(argv2));
arg1 = 0;
arg2 = 0;
arg = 0;
index = 0;
}
/* Run a command. Commands are defined in commands.h */
int runCommand() {
int i = 0;
char *p = argv1;
char *str;
int pid_args[4];
arg1 = atoi(argv1);
arg2 = atoi(argv2);
switch(cmd) {
case GET_BAUDRATE:
Serial.println(BAUDRATE);
break;
case ANALOG_READ:
Serial.println(analogRead(arg1));
break;
case DIGITAL_READ:
Serial.println(digitalRead(arg1));
break;
case ANALOG_WRITE:
analogWrite(arg1, arg2);
Serial.println("OK");
break;
case DIGITAL_WRITE:
if (arg2 == 0) digitalWrite(arg1, LOW);
else if (arg2 == 1) digitalWrite(arg1, HIGH);
Serial.println("OK");
break;
case PIN_MODE:
if (arg2 == 0) pinMode(arg1, INPUT);
else if (arg2 == 1) pinMode(arg1, OUTPUT);
Serial.println("OK");
break;
case PING:
Serial.println(Ping(arg1));
break;
#ifdef USE_SERVOS
case SERVO_WRITE:
servos[arg1].setTargetPosition(arg2);
Serial.println("OK");
break;
case SERVO_READ:
Serial.println(servos[arg1].getServo().read());
break;
#endif
#ifdef USE_BASE
case READ_ENCODERS:
Serial.print(readEncoder(LEFT));
Serial.print(" ");
Serial.println(readEncoder(RIGHT));
break;
case RESET_ENCODERS:
resetEncoders();
resetPID();
Serial.println("OK");
break;
case MOTOR_SPEEDS:
/* Reset the auto stop timer */
lastMotorCommand = millis();
if (arg1 == 0 && arg2 == 0) {
setMotorSpeeds(0, 0);
resetPID();
moving = 0;
}
else moving = 1;
leftPID.TargetTicksPerFrame = arg1;
rightPID.TargetTicksPerFrame = arg2;
Serial.println("OK");
break;
case MOTOR_RAW_PWM:
/* Reset the auto stop timer */
lastMotorCommand = millis();
resetPID();
moving = 0; // Sneaky way to temporarily disable the PID
setMotorSpeeds(arg1, arg2);
Serial.println("OK");
break;
case UPDATE_PID:
while ((str = strtok_r(p, ":", &p)) != '\0') {
pid_args[i] = atoi(str);
i++;
}
Kp = pid_args[0];
Kd = pid_args[1];
Ki = pid_args[2];
Ko = pid_args[3];
Serial.println("OK");
break;
#endif
default:
Serial.println("Invalid Command");
break;
}
}
/* Setup function--runs once at startup. */
void setup() {
Serial.begin(BAUDRATE);
// Initialize the motor controller if used */
#ifdef USE_BASE
#ifdef ARDUINO_ENC_COUNTER
//set as inputs
DDRD &= ~(1<<LEFT_ENC_PIN_A);
DDRD &= ~(1<<LEFT_ENC_PIN_B);
DDRC &= ~(1<<RIGHT_ENC_PIN_A);
DDRC &= ~(1<<RIGHT_ENC_PIN_B);
//enable pull up resistors
PORTD |= (1<<LEFT_ENC_PIN_A);
PORTD |= (1<<LEFT_ENC_PIN_B);
PORTC |= (1<<RIGHT_ENC_PIN_A);
PORTC |= (1<<RIGHT_ENC_PIN_B);
// tell pin change mask to listen to left encoder pins
PCMSK2 |= (1 << LEFT_ENC_PIN_A)|(1 << LEFT_ENC_PIN_B);
// tell pin change mask to listen to right encoder pins
PCMSK1 |= (1 << RIGHT_ENC_PIN_A)|(1 << RIGHT_ENC_PIN_B);
// enable PCINT1 and PCINT2 interrupt in the general interrupt mask
PCICR |= (1 << PCIE1) | (1 << PCIE2);
#endif
initMotorController();
resetPID();
#endif
/* Attach servos if used */
#ifdef USE_SERVOS
int i;
for (i = 0; i < N_SERVOS; i++) {
servos[i].initServo(
servoPins[i],
stepDelay[i],
servoInitPosition[i]);
}
#endif
}
/* Enter the main loop. Read and parse input from the serial port
and run any valid commands. Run a PID calculation at the target
interval and check for auto-stop conditions.
*/
void loop() {
while (Serial.available() > 0) {
// Read the next character
chr = Serial.read();
// Terminate a command with a CR
if (chr == 13) {
if (arg == 1) argv1[index] = NULL;
else if (arg == 2) argv2[index] = NULL;
runCommand();
resetCommand();
}
// Use spaces to delimit parts of the command
else if (chr == ' ') {
// Step through the arguments
if (arg == 0) arg = 1;
else if (arg == 1) {
argv1[index] = NULL;
arg = 2;
index = 0;
}
continue;
}
else {
if (arg == 0) {
// The first arg is the single-letter command
cmd = chr;
}
else if (arg == 1) {
// Subsequent arguments can be more than one character
argv1[index] = chr;
index++;
}
else if (arg == 2) {
argv2[index] = chr;
index++;
}
}
}
// If we are using base control, run a PID calculation at the appropriate intervals
#ifdef USE_BASE
if (millis() > nextPID) {
updatePID();
nextPID += PID_INTERVAL;
}
// Check to see if we have exceeded the auto-stop interval
if ((millis() - lastMotorCommand) > AUTO_STOP_INTERVAL) {;
setMotorSpeeds(0, 0);
moving = 0;
}
#endif
// Sweep servos
#ifdef USE_SERVOS
int i;
for (i = 0; i < N_SERVOS; i++) {
servos[i].doSweep();
}
#endif
}
Encoder Pin Designations:
/* *************************************************************
Encoder driver function definitions - by James Nugen
************************************************************ */
#ifdef ARDUINO_ENC_COUNTER
//below can be changed, but should be PORTD pins;
//otherwise additional changes in the code are required
#define LEFT_ENC_PIN_A PD2 //pin 2
#define LEFT_ENC_PIN_B PD3 //pin 3
//below can be changed, but should be PORTC pins
#define RIGHT_ENC_PIN_A PC4 //pin A4
#define RIGHT_ENC_PIN_B PC5 //pin A5
#endif
long readEncoder(int i);
void resetEncoder(int i);
void resetEncoders();
Encoder Driver:
/* *************************************************************
Encoder definitions
Add an "#ifdef" block to this file to include support for
a particular encoder board or library. Then add the appropriate
#define near the top of the main ROSArduinoBridge.ino file.
************************************************************ */
#ifdef USE_BASE
#ifdef ROBOGAIA
/* The Robogaia Mega Encoder shield */
#include "MegaEncoderCounter.h"
/* Create the encoder shield object */
MegaEncoderCounter encoders = MegaEncoderCounter(4); // Initializes the Mega Encoder Counter in the 4X Count mode
/* Wrap the encoder reading function */
long readEncoder(int i) {
if (i == LEFT) return encoders.YAxisGetCount();
else return encoders.XAxisGetCount();
}
/* Wrap the encoder reset function */
void resetEncoder(int i) {
if (i == LEFT) return encoders.YAxisReset();
else return encoders.XAxisReset();
}
#elif defined(ARDUINO_ENC_COUNTER)
volatile long left_enc_pos = 0L;
volatile long right_enc_pos = 0L;
static const int8_t ENC_STATES [] = {0,1,-1,0,-1,0,0,1,1,0,0,-1,0,-1,1,0}; //encoder lookup table
/* Interrupt routine for LEFT encoder, taking care of actual counting */
ISR (PCINT2_vect){
static uint8_t enc_last=0;
enc_last <<=2; //shift previous state two places
enc_last |= (PIND & (3 << 2)) >> 2; //read the current state into lowest 2 bits
left_enc_pos += ENC_STATES[(enc_last & 0x0f)];
}
/* Interrupt routine for RIGHT encoder, taking care of actual counting */
ISR (PCINT1_vect){
static uint8_t enc_last=0;
enc_last <<=2; //shift previous state two places
enc_last |= (PINC & (3 << 4)) >> 4; //read the current state into lowest 2 bits
right_enc_pos += ENC_STATES[(enc_last & 0x0f)];
}
/* Wrap the encoder reading function */
long readEncoder(int i) {
if (i == LEFT) return left_enc_pos;
else return right_enc_pos;
}
/* Wrap the encoder reset function */
void resetEncoder(int i) {
if (i == LEFT){
left_enc_pos=0L;
return;
} else {
right_enc_pos=0L;
return;
}
}
#else
#error A encoder driver must be selected!
#endif
/* Wrap the encoder reset function */
void resetEncoders() {
resetEncoder(LEFT);
resetEncoder(RIGHT);
}
#endif
I think if you use a Mega instead of an Uno, the pin ports are different.
So change the port from PD4 to PE4 and PD3 to PE5. Also, change PC4 to PF4 and PC5 to PF5.
In the Encoder.ino, you also have to change the ports accordingly.
Encoder.h:
#define LEFT_ENC_PIN_A PE4 //pin 2
#define LEFT_ENC_PIN_B PE5 //pin 3
//below can be changed, but should be PORTC pins
#define RIGHT_ENC_PIN_A PF5 //pin A4
#define RIGHT_ENC_PIN_B PF5 //pin A5
Encoder.ino:
/* Interrupt routine for LEFT encoder, taking care of actual counting */
ISR (PCINT2_vect){
static uint8_t enc_last=0;
enc_last <<=2; //shift previous state two places
enc_last |= (PINE & (3 << 2)) >> 2; //read the current state into lowest 2 bits
left_enc_pos += ENC_STATES[(enc_last & 0x0f)];
}
/* Interrupt routine for RIGHT encoder, taking care of actual counting */
ISR (PCINT1_vect){
static uint8_t enc_last=0;
enc_last <<=2; //shift previous state two places
enc_last |= (PINF & (3 << 4)) >> 4; //read the current state into lowest 2 bits
right_enc_pos += ENC_STATES[(enc_last & 0x0f)];
}
Related
I am using Arduino_STM32 rogerclark's library.https://github.com/rogerclarkmelbourne/Arduino_STM32 .
Now I want to Develop an In Application Programming(IAP) like a bootloader. Take Code from SD card and Store in Controller flash at 0x8010000 and then jump to that location and run the loaded new application.
the code took from SD and stored into flash successfully done but after jump function called its printing null like this
13:29:04.933 [RX] - Starts............
13:29:07.970 [RX] - 20480 uploaded successfully.
NULNULNULNUL NULNUL
my Main IAP code is
Header file
#include <SPI.h>
#include <SD.h>
#include <EEPROM.h>
#include <stdint.h>
#include "libmaple/scb.h"
#include "usb_lib.h"
typedef void (*FuncPtr)(void);
#define SCS_BASE ((u32)0xE000E000)
#define NVIC_BASE (SCS_BASE + 0x0100)
#define SCB_BASE (SCS_BASE + 0x0D00)
#define SCS 0xE000E000
#define NVIC (SCS+0x100)
#define SCB (SCS+0xD00)
#define STK (SCS+0x10)
#define SCB_VTOR (SCB+0x08)
#define STK_CTRL (STK+0x00)
#define RCC ((u32)0x40021000)
#define RCC_CR RCC
#define RCC_CFGR (RCC + 0x04)
#define RCC_CIR (RCC + 0x08)
#define USB_LP_IRQ ((u8)0x14)
#define SET_REG(addr,val) do{ *(volatile uint32_t*)(addr)=val;} while(0)
#define GET_REG(addr) (*(vu32*)(addr))
#define pRCC ((rcc_reg_map *) RCC)
typedef struct {
u8 NVIC_IRQChannel;
u8 NVIC_IRQChannelPreemptionPriority;
u8 NVIC_IRQChannelSubPriority;
bool NVIC_IRQChannelCmd; /* TRUE for enable */
} NVIC_InitTypeDef;
#define RegBase (0x40005C00L)
#define CNTR ((volatile unsigned *)(RegBase + 0x40))
#define _SetCNTR(wRegValue) (*CNTR = (u16)wRegValue)
#define _GetCNTR() ((u16) *CNTR)
#define ISTR ((volatile unsigned *)(RegBase + 0x44))
#define _SetISTR(wRegValue) (*ISTR = (u16)wRegValue)
#define _GetISTR() ((u16) *ISTR)
void setupFLASH();
void usbDsbISR(void);
void nvicInit(NVIC_InitTypeDef *NVIC_InitStruct);
void nvicDisableInterrupts();
void setMspAndJump(u32 usrAddr);
void systemReset(void);
RESULT usbPowerOff(void);
void setupFLASH()
{
/* configure the HSI oscillator */
if ((pRCC->CR & 0x01) == 0x00)
{
u32 rwmVal = pRCC->CR;
rwmVal |= 0x01;
pRCC->CR = rwmVal;
}
/* wait for it to come on */
while ((pRCC->CR & 0x02) == 0x00) {}
}
void usbDsbISR(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = USB_LP_IRQ;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = FALSE;
nvicInit(&NVIC_InitStructure);
}
void nvicInit(NVIC_InitTypeDef *NVIC_InitStruct)
{
u32 tmppriority = 0x00;
u32 tmpreg = 0x00;
u32 tmpmask = 0x00;
u32 tmppre = 0;
u32 tmpsub = 0x0F;
scb_reg_map *rSCB = (scb_reg_map *) SCB_BASE;
nvic_reg_map *rNVIC = (nvic_reg_map *) NVIC_BASE;
/* Compute the Corresponding IRQ Priority --------------------------------*/
tmppriority = (0x700 - (rSCB->AIRCR & (u32)0x700)) >> 0x08;
tmppre = (0x4 - tmppriority);
tmpsub = tmpsub >> tmppriority;
tmppriority = (u32)NVIC_InitStruct->NVIC_IRQChannelPreemptionPriority << tmppre;
tmppriority |= NVIC_InitStruct->NVIC_IRQChannelSubPriority & tmpsub;
tmppriority = tmppriority << 0x04;
tmppriority = ((u32)tmppriority) << ((NVIC_InitStruct->NVIC_IRQChannel & (u8)0x03) * 0x08);
tmpreg = rNVIC->IP[(NVIC_InitStruct->NVIC_IRQChannel >> 0x02)];
tmpmask = (u32)0xFF << ((NVIC_InitStruct->NVIC_IRQChannel & (u8)0x03) * 0x08);
tmpreg &= ~tmpmask;
tmppriority &= tmpmask;
tmpreg |= tmppriority;
rNVIC->IP[(NVIC_InitStruct->NVIC_IRQChannel >> 0x02)] = tmpreg;
/* Enable the Selected IRQ Channels --------------------------------------*/
rNVIC->ISER[(NVIC_InitStruct->NVIC_IRQChannel >> 0x05)] =
(u32)0x01 << (NVIC_InitStruct->NVIC_IRQChannel & (u8)0x1F);
}
void nvicDisableInterrupts()
{
nvic_reg_map *rNVIC = (nvic_reg_map *) NVIC_BASE;
rNVIC->ICER[0] = 0xFFFFFFFF;
rNVIC->ICER[1] = 0xFFFFFFFF;
rNVIC->ICPR[0] = 0xFFFFFFFF;
rNVIC->ICPR[1] = 0xFFFFFFFF;
SET_REG(STK_CTRL, 0x04); /* disable the systick, which operates separately from nvic */
}
void usbDsbBus(void)
{
// setPin(USB_DISC_BANK,USB_DISC_PIN);
usbPowerOff();
// SET_REG(USB_DISC_CR,
// (GET_REG(USB_DISC_CR) & USB_DISC_CR_MASK) | USB_DISC_CR_OUTPUT);
// resetPin(USB_DISC_BANK, USB_DISC_PIN); /* Pull DP+ down */
// volatile unsigned x = 500000; do { ; }while(--x);
// SET_REG(USB_DISC_CR,
// (GET_REG(USB_DISC_CR) & USB_DISC_CR_MASK) | USB_DISC_CR_INPUT); //Sets the PA12 as floating
input
}
RESULT usbPowerOff(void)
{
#define CNTR_PDWN (0x0002) /* Power DoWN */
#define CNTR_FRES (0x0001) /* Force USB RESet */
_SetCNTR(CNTR_FRES);
_SetISTR(0);
_SetCNTR(CNTR_FRES + CNTR_PDWN);
/* note that all weve done here is powerdown the
usb peripheral. we have no disabled the clocks,
pulled the USB_DISC_PIN pin back up, or reset the
application state machines */
return USB_SUCCESS;
}
void systemReset(void)
{
SET_REG(RCC_CR, GET_REG(RCC_CR) | 0x00000001);
SET_REG(RCC_CFGR, GET_REG(RCC_CFGR) & 0xF8FF0000);
SET_REG(RCC_CR, GET_REG(RCC_CR) & 0xFEF6FFFF);
SET_REG(RCC_CR, GET_REG(RCC_CR) & 0xFFFBFFFF);
SET_REG(RCC_CFGR, GET_REG(RCC_CFGR) & 0xFF80FFFF);
SET_REG(RCC_CIR, 0x00000000); /* disable all RCC interrupts */
}
void setMspAndJump(u32 usrAddr)
{
// Dedicated function with no call to any function (appart the last call)
// This way, there is no manipulation of the stack here, ensuring that GGC
// didn't insert any pop from the SP after having set the MSP.
typedef void (*funcPtr)(void);
u32 jumpAddr = *(vu32 *)(usrAddr + 0x04); /* reset ptr in vector table */
funcPtr usrMain = (funcPtr) jumpAddr;
SET_REG(SCB_VTOR, (vu32) (usrAddr));
asm volatile("msr msp, %0"::"g"(*(volatile u32 *)usrAddr));
usrMain(); /* go! */
}
main code is
#include "core_test.h"
#define CS PB9
File myFile;
char Name[15] = "ASCII.bin";
uint32_t Count = 0;
uint32_t total = 0;
#define FLASH_FLAG_EOP ((uint32_t)0x00000020) /* FLASH End of Operation flag */
#define FLASH_FLAG_PGERR ((uint32_t)0x00000004) /* FLASH Program error flag */
#define FLASH_FLAG_WRPRTERR ((uint32_t)0x00000010) /* FLASH Write protected error flag */
#define myFLASH_APP_ADDR 0x08000000
#define FLASH_APP_ADDR 0x08010000 //The first application start address (stored in FLASH)
#define STM_PAGE_SIZE 2048 //Note: The FLASH page size of STM32F103ZET6 is 2K.
//****************************************************************************************************
// Global variable declaration
char buff[STM_PAGE_SIZE];
int res;
unsigned int br;
void Jump2App(uint32_t Addr)
{
if (((*(uint32_t*)Addr) & 0x2FFE0000) == 0x20000000) //Check if the top address of the stack is legal.
{
// FLASH_Lock();
usbDsbISR(); //Serial1.println("1");
nvicDisableInterrupts(); //Serial1.println("2");
usbDsbBus(); //Serial1.println("3");
// Does nothing, as PC12 is not connected on teh Maple mini according to the schemmatic setPin(GPIOC, 12); // disconnect usb from host. todo, macroize pin
systemReset(); // resets clocks and periphs, not core regs
//Serial1.println("4");
setMspAndJump(Addr);
}
}
void FirmwareUpdate(void)
{
int PageOffest = 0;
int ByteOffest;
if (! IsFileExists(Name)) return;
myFile = SD.open(Name);
while (1)
{
if (Read_data_from_File(buff))
{
FLASH_Unlock();
// FLASH_ClearFlag(((uint16_t)0x00000034));
// FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR);
FLASH_ErasePage(FLASH_APP_ADDR + PageOffest);
for (ByteOffest = 0; ByteOffest < STM_PAGE_SIZE; ByteOffest += 2)
{
total = total + 2;
FLASH_ProgramHalfWord(FLASH_APP_ADDR + PageOffest + ByteOffest, *(uint16_t*)(buff + ByteOffest));
}
FLASH_Lock();
PageOffest += STM_PAGE_SIZE;
// Serial1.println(PageOffest);
}
else if (myFile.size() <= total) break;
}
myFile.close();
Serial1.println(total);
//myFile.close();
}
void setup()
{
afio_cfg_debug_ports(AFIO_DEBUG_SW_ONLY);
Serial1.begin(9600);
if (!SD.begin(CS))
{
Serial1.println("No SD............");
Jump2App(FLASH_APP_ADDR);
}
delay(1000);
Serial1.println("Starts............"); delay(2000);
FirmwareUpdate();
Jump2App(FLASH_APP_ADDR);
while (1);
}
void loop()
{}
bool IsFileExists(char FileName[])
{
if (SD.exists(FileName)) return 1;
else return 0;
}
bool Read_data_from_File(char str[])
{
memset(str, 255, 2048);
uint16_t i = 0;
if (myFile.size() < total)
{
//memset(str, 255, 2048);
// Serial1.println("File Closed");
// Serial1.println(total);
return 0;
}
if (myFile)
{
while (i < 2048)
{
str[i++] = myFile.read();
Count = Count + 1;
if (myFile.size() < Count)
{
//memset(str, 255, 2048);
// Serial1.println("File Closed");
// Serial1.println(Count);
return 1;
}
}
}
else return 0;
}
my user Application code is ASCIItable example code which is given in arduino
before generation this ASCII.bin file
i have changed ROM location address 0x8000000 to 0x8010000 and compiled the file.
Is this process correct,
please help me where I am doing wrong
I am currently trying to send a float value across two Arduinos via SPI. Currently I am working to send a static value of 2.25 across and then read it via the Serial.println() command. I would then want to pass a float value from a linear displacement sensor. My end goal is to be able to have the master ask for information, the slave gathers the appropriate data and packages it and then master receives said data and does what it needs with it.
Currently I am getting an error "call of overloaded 'println(byte [7])' is ambiguous" and I am not to sure why I am getting this error. I am currently a mechanical engineering student and I am crash-coursing myself through C/C++. I am not entirely positive about what I am doing. I know that a float is 4 bytes and I am attempting to create a buffer of 7 bytes to store the float and the '\n' char with room to spare. My current code is below.
Master:
#include <SPI.h>
void setup() {
pinMode(SS,OUTPUT);
digitalWrite(SS,HIGH);
SPI.begin();
SPI.setClockDivider(SPI_CLOCK_DIV4);
}
void loop() {
digitalWrite(SS,LOW);
float a = 2.25;
SPI.transfer(a);
SPI.transfer('\n');
digitalWrite(SS,HIGH);
}
My slave code is as follows:
#include <SPI.h>
byte buf[7];
volatile byte pos = 0;
volatile boolean process_it = false;
void setup() {
Serial.begin(9600);
pinMode(MISO,OUTPUT);
digitalWrite(MISO,LOW);
SPCR |= _BV(SPE); // SPI Enable, sets this Arduino to Slave
SPCR |= _BV(SPIE); // SPI interrupt enabled
}
ISR(SPI_STC_vect) {
// Interrupt Service Routine(SPI_(SPI Transfer Complete)_vector)
byte c = SPDR;
// SPDR = SPI Data Register, so you are saving the byte of information in that register to byte c
if (pos < sizeof buf) {
buf[pos++] = c;
if (c == '\n') {
process_it = true;
}
}
}
void loop() {
if (process_it = true) {
Serial.println(buf);
pos = 0;
process_it = false;
}
}
I figured out what I needed to do and I wanted to post my finished code. I also added an ability to transfer more than one float value.
Master:
#include <SPI.h>
float a = 3.14;
float b = 2.25;
uint8_t storage [12];
float buff[2] = {a, b};
void setup()
{
digitalWrite(SS, HIGH);
SPI.begin();
Serial.begin(9600);
SPI.setClockDivider(SPI_CLOCK_DIV8);
}
void loop()
{
digitalWrite(SS, LOW);
memcpy(storage, &buff, 8);
Serial.print("storage[0] = "); Serial.println(storage[0]); // the
following serial prints were to check i was getting the right decimal
numbers for the floats.
Serial.print("storage[1] = "); Serial.println(storage[1]);
Serial.print("storage[2] = "); Serial.println(storage[2]);
Serial.print("storage[3] = "); Serial.println(storage[3]);
Serial.print("storage[4] = "); Serial.println(storage[4]);
Serial.print("storage[5] = "); Serial.println(storage[5]);
Serial.print("storage[6] = "); Serial.println(storage[6]);
Serial.print("storage[7] = "); Serial.println(storage[7]);
SPI.transfer(storage, sizeof storage ); //SPI library allows a user to
transfer a whole array of bytes and you need to include the size of the
array.
digitalWrite(SS, HIGH);
delay(1000);
}
For my Slave code:
#include <SPI.h>
byte storage [8];
volatile byte pos;
volatile boolean process;
float buff[2];
void setup()
{
pinMode(MISO,OUTPUT);
SPCR |= _BV(SPE);
SPCR |= _BV(SPIE);
pos = 0;
process = false;
Serial.begin(9600);
}
ISR(SPI_STC_vect)
{
byte gathered = SPDR;
if( pos < sizeof storage)
{
storage[pos++] = gathered;
}
else
process = true;
}
void loop()
{
if( process )
{
Serial.print("storage[0] = "); Serial.println(storage[0]);
Serial.print("storage[1] = "); Serial.println(storage[1]);
Serial.print("storage[2] = "); Serial.println(storage[2]);
Serial.print("storage[3] = "); Serial.println(storage[3]);
Serial.print("storage[4] = "); Serial.println(storage[4]);
Serial.print("storage[5] = "); Serial.println(storage[5]);
Serial.print("storage[6] = "); Serial.println(storage[6]);
Serial.print("storage[7] = "); Serial.println(storage[7]);
memcpy(buff,&storage,8);
Serial.print("This is buff[0]");Serial.println(buff[0]);
Serial.print("This is buff[1]");Serial.println(buff[1]);
storage[pos] = 0;
pos = 0;
process = false;
}
}
The immediate problem is that Serial.print doesn't know what to do with a byte array. Either declare it as a char array or cast it in the print statement:
char buf[7];
OR
Serial.print((char*) buf);
Either way, though, it's not going to show up as a float like you want.
An easier way to do all this is to use memcpy or a union to go back and forth between float and bytes. On the master end:
uint8_t buf[4];
memcpy(buf, &a, 4);
Then use SPI to send 4 bytes. Reverse it on the peripheral end.
Note that sending '\n' as the termination byte is a bad idea because it can lead to weird behavior, since one of the bytes in the float could easily be 0x0a, the hexadecimal equivalent of '\n'.
I'm trying to write my own basic libraries to program the Arduino in pure C++. I've tried using a variadic function to implement something similar to Linux's ioctl() to control the SPI module but it just won't work and I have no idea why. I don't pin 13 (Arduino SCK) light up as expected during SPI transactions indicating that SPI is not operating. All the other functions in my library work properly.
The following is my SPI library:
/*
spi.h: SPI driver for Atmega328p
*/
#ifndef _SPI_H
#define _SPI_H
#include <avr/io.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdarg.h>
#include <inttypes.h>
// SPI bus pin mapping ///////////////////////////////////
#define PORT_SPI PORTB // Port register containing SPI pins
#define DDR_SPI DDRB // Data direction register containing SPI pins
#define DDR_SCK DDB5 // Data direction bit of SPI SCK pin
#define DDR_MISO DDB4 // Data direction bit of SPI MISO pin
#define DDR_MOSI DDB3 // Data direction bit of SPI MOSI pin
#define DDR_HWCS DDB2 // Data direction bit of SPI hardware chip select pin
#define PIN_SCK PB5 // Port register bit of SPI SCK pin
#define PIN_MISO PB4 // Port register bit of SPI MISO pin
#define PIN_MOSI PB3 // Port register bit of SPI MOSI pin
#define PIN_HWCS PB2 // Port register bit of SPI hardware chip select pin
// SPI ioctl commands ////////////////////////////////////
#define SPIIOCCONF 0 // Configure SPI command
#define SPIIOCDECONF 1 // Deconfigure SPI command
#define SPIIOCTRANSMIT 2 // SPI byte exchange command
// Clock frequency settings //////////////////////////////
#define SCK_DIV2 2 // Divide source pulse by 2
#define SCK_DIV4 4 // Divide source pulse by 4
#define SCK_DIV8 8 // Divide source pulse by 8
#define SCK_DIV16 16 // Divide source pulse by 16
#define SCK_DIV32 32 // Divide source pulse by 32
#define SCK_DIV64 64 // Divide source pulse by 64
#define SCK_DIV128 128 // Divide source pulse by 128
// SPI modes /////////////////////////////////////////////
#define SPI_MODE0 0
#define SPI_MODE1 1
#define SPI_MODE2 2
#define SPI_MODE3 3
// SPI transaction data orders ///////////////////////////
#define LSBFIRST 0
#define MSBFIRST 1
// The SPI module ////////////////////////////////////////
class spiModule {
private:
bool configured; // Indicates whether SPI is operating with a valid configuration
uint8_t ddrOld, portOld; // Value of DDR_SPI and PORT_SPI just before an SPI configuration was called for
// ( These variables are used to restore the state of the
// SPI pins when SPI is deconfigured )
/* ioctls used to operate the SPI module */
void spiiocconf(int, int, int); // Configure SPI with a valid clock frequency, data order and SPI mode
void spiiocdeconf(void); // Deconfigure SPI and restore SPI pins to their original states
void spiioctransmit(uint8_t, uint8_t *); // Exchange a byte of data over SPI
/* ioctl handlers */
/* These routines check the validity of the arguments and call the ioctls (above) only if all arguments make sense */
/* I've tested these functions by making them public and found that they work perfectly */
int conf(int, int, int); // call spiiocconf() if arguments are valid and SPI is configured
int deconf(void); // call spiiocdeconf() if all arguments are valid and SPI is configured
int transmit(uint8_t, uint8_t *); // call spiioctransmit() if all arguments are valid and SPI is configured
public:
spiModule(void); // Initialize this class
int ioctl(int action, ... ); // Core ioctl handler (supposed to work like the Linux ioctl() system call). But this one just won't work.
};
spiModule spi; // Object of class spiModule for using SPI
// Constructor ///////////////////////////////////////////
spiModule::spiModule(void) {
configured = false;
}
// Private routines //////////////////////////////////////
/* Ioctls */
void spiModule::spiiocconf(int clkDiv, int dataOrder, int mode) {
// Store the values of DDR_SPI and PORT_SPI so they may be recovered when SPI is deconfigured
ddrOld = DDR_SPI;
portOld = PORT_SPI;
// Configure SCK, MOSI and HWCS as output pins and MISO as an input pin
DDR_SPI |= (_BV(DDR_HWCS) | _BV(DDR_SCK) | _BV(DDR_MOSI));
DDR_SPI &= ~_BV(DDR_MISO);
// Power up the SPI module
PRR &= ~_BV(PRSPI);
// Enable SPI and configure it as master
SPCR = 0x00;
SPCR |= (_BV(SPE) | _BV(MSTR));
// Set data order
switch(dataOrder)
{
case LSBFIRST:
SPCR |= _BV(DORD);
break;
case MSBFIRST:
SPCR &= ~_BV(DORD);
break;
}
// Set SPI mode
switch(mode)
{
case SPI_MODE0:
SPCR &= ~(_BV(CPOL) | _BV(CPHA));
break;
case SPI_MODE1:
SPCR |= _BV(CPHA);
SPCR &= ~_BV(CPOL);
break;
case SPI_MODE2:
SPCR &= ~_BV(CPHA);
SPCR |= _BV(CPOL);
break;
case SPI_MODE3:
SPCR |= (_BV(CPOL) | _BV(CPHA));
break;
}
// Set SPI clock frequency
switch(clkDiv)
{
case SCK_DIV2:
SPCR &= ~(_BV(SPR0) | _BV(SPR1));
SPSR |= _BV(SPI2X);
break;
case SCK_DIV4:
SPCR &= ~(_BV(SPR0) | _BV(SPR1));
SPSR &= ~_BV(SPI2X);
break;
case SCK_DIV8:
SPCR |= _BV(SPR0);
SPCR &= ~_BV(SPR1);
SPSR |= _BV(SPI2X);
break;
case SCK_DIV16:
SPCR |= _BV(SPR0);
SPCR &= ~_BV(SPR1);
SPSR &= ~_BV(SPI2X);
break;
case SCK_DIV32:
SPCR &= ~_BV(SPR0);
SPCR |= _BV(SPR1);
SPSR |= _BV(SPI2X);
break;
case SCK_DIV64:
SPCR |= _BV(SPR0);
SPCR |= _BV(SPR1);
SPSR |= _BV(SPI2X);
break;
case SCK_DIV128:
SPCR |= _BV(SPR0);
SPCR |= _BV(SPR1);
SPSR &= ~_BV(SPI2X);
break;
}
// SPI is now configured
configured = true;
return;
}
void spiModule::spiiocdeconf(void) {
// Clear SPI configuration, power down the SPI module and restore the values of DDR_SPI and PORT_SPI
SPCR = 0x00;
PRR |= _BV(PRSPI);
DDR_SPI = ddrOld;
PORT_SPI = portOld;
// SPI is no longer configured
configured = false;
return;
}
void spiModule::spiioctransmit(uint8_t txbyte, uint8_t * rxbyte) {
// Write TX byte to data register
SPDR = txbyte;
while(!(SPSR & _BV(SPIF)))
{
/* wait for data transmission to complete */
}
SPSR &= ~_BV(SPIF);
// Return RX byte by storing it at the specified location
if(rxbyte != NULL)
{
*rxbyte = SPDR;
}
return;
}
/* Ioctl handlers (verify that all arguments are appropriate and only then proceed with the ioctl) */
int spiModule::conf(int clkDiv, int dataOrder, int mode) {
// Return with error of SPI is not configured
if(!configured)
{
return -1;
}
// Verify validity of clkDiv (clock pulse division factor)
switch(clkDiv)
{
case SCK_DIV2:
break;
case SCK_DIV4:
break;
case SCK_DIV8:
break;
case SCK_DIV16:
break;
case SCK_DIV32:
break;
case SCK_DIV64:
break;
case SCK_DIV128:
break;
default:
return -1;
}
// Verify validity of dataOrder (order of byte transfer)
switch(dataOrder)
{
case LSBFIRST:
break;
case MSBFIRST:
break;
default:
return -1;
}
// Check validity of mode (SPI mode)
switch(mode)
{
case SPI_MODE0:
break;
case SPI_MODE1:
break;
case SPI_MODE2:
break;
case SPI_MODE3:
break;
default:
return -1;
}
// If all goes well, execute the ioctl
spiiocconf(clkDiv, dataOrder, mode);
return 0;
}
int spiModule::deconf(void) {
// If SPI is configured, deconfigure it
if(!configured)
{
return -1;
}
spiiocdeconf();
return 0;
}
int spiModule::transmit(uint8_t tx, uint8_t * rx) {
// If SPI is configured, make a byte exchange
if(!configured)
{
return -1;
}
spiioctransmit(tx, rx);
return 0;
}
// Public routines ///////////////////////////////////////
int spiModule::ioctl(int action, ... ) {
// This routine checks the value of action and executes the respective ioctl
// It returns with error if the value of action is not valid
va_list ap;
int clkDiv, dataOrder, mode;
uint8_t txbyte;
uint8_t * rxbyte;
int retVal;
switch(action)
{
case SPIIOCCONF:
va_start(ap, action);
clkDiv = va_arg(ap, int);
dataOrder = va_arg(ap, int);
mode = va_arg(ap, int);
va_end(ap);
retVal = conf(clkDiv, dataOrder, mode);
return retVal;
case SPIIOCDECONF:
retVal = deconf();
return retVal;
case SPIIOCTRANSMIT:
va_start(ap, action);
txbyte = va_arg(ap, uint8_t);
rxbyte = va_arg(ap, uint8_t*);
va_end(ap);
retVal = transmit(txbyte, rxbyte);
return retVal;
default:
return -1;
}
}
#endif
I'm compiling and uploading my code to the Arduino using the following commands (spiTest.cpp is a code that I used to test this library)
COMPILER=~/Softwares/arduino-1.6.8/hardware/tools/avr/bin/avr-g++
HEXGENERATOR=~/Softwares/arduino-1.6.8/hardware/tools/avr/bin/avr-objcopy
UPLOADER=~/Softwares/arduino-1.6.8/hardware/tools/avr/bin/avrdude
AVRDUDE_CFG=~/Softwares/arduino-1.6.8/hardware/tools/avr/etc/avrdude.conf
$COMPILER -c -g -w -D F_CPU=16000000UL -mmcu=atmega328p -std=gnu++11 -o spiTest.o spiTest.cpp
$COMPILER -mmcu=atmega328p spiTest.o -o spiTest
$HEXGENERATOR -O ihex -R .eeprom spiTest spiTest.hex
$UPLOADER -C $AVRDUDE_CFG -v -p atmega328p -c arduino -P /dev/ttyACM0 -b 115200 -D -U flash:w:spiTest.hex:i
I've used variadic functions to implement ioctl() before and it worked when I used the Arduino IDE to compile and upload my program. I don't understand what's preventing variadic functions from working properly in this code.
You are in the C++, you can do it in better. For example something like:
class SPIIOCONF_t {} SPIIOCONF;
class SPIIOCDECONF_t {} SPIIOCDECONF;
class SPIIOCTRANSMIT_t {} SPIIOCTRANSMIT;
int ioctl(SPIIOCONF_t, int clkDiv, int dataOrder, int mode) {
return conf(clkDiv, dataOrder, mode);
}
int ioctl(SPIIOCDECONF_t) {
return deconf();
}
int ioctl(SPIIOCTRANSMIT_t, uint8_t txbyte, uint8_t rxbyte) {
return transmit(txbyte, rxbyte);
}
void setup() {
Serial.begin(115200);
Serial.println(ioctl(SPIIOCONF, 10, 1, 1));
Serial.println(ioctl(SPIIOCDECONF));
uint8_t rx;
Serial.println(ioctl(SPIIOCTRANSMIT, 0xFF, &rx));
}
or similarly without defining dummy class instance, but you have to create one in the call:
class SPIIOCONF {};
class SPIIOCDECONF {};
class SPIIOCTRANSMIT {};
int ioctl(SPIIOCONF, int clkDiv, int dataOrder, int mode) {
return conf(clkDiv, dataOrder, mode);
}
int ioctl(SPIIOCDECONF) {
return deconf();
}
int ioctl(SPIIOCTRANSMIT, uint8_t txbyte, uint8_t rxbyte) {
return transmit(txbyte, rxbyte);
}
void setup() {
ioctl(SPIIOCONF{}, 10, 1, 1);
uint8_t rx;
Serial.println(ioctl(SPIIOCTRANSMIT{}, 0xFF, &rx));
ioctl(SPIIOCDECONF{});
}
I am working on a project, syncing Nintendo Nunchuk with Arduino. I found a code online for the same from http://letsmakerobots.com/node/5684
Here, is the code
#include <Wire.h>;
void setup(){
Serial.begin(19200);
nunchuck_setpowerpins();
nunchuck_init();
Serial.print("Nunchuck ready\n");
}
void loop(){
nunchuck_get_data();
nunchuck_print_data();
delay(1000);
}
//======================================================================================================================================================================================================//
//Do not modify!!!!!!!!
//======================================================================================================================================================================================================//
//
// Nunchuck functions
//
static uint8_t nunchuck_buf[6]; // array to store nunchuck data,
// Uses port C (analog in) pins as power & ground for Nunchuck
static void nunchuck_setpowerpins()
{
#define pwrpin PORTC3
#define gndpin PORTC2
DDRC |= _BV(pwrpin) | _BV(gndpin);
PORTC &=~ _BV(gndpin);
PORTC |= _BV(pwrpin);
delay(100); // wait for things to stabilize
}
// initialize the I2C system, join the I2C bus,
// and tell the nunchuck we're talking to it
void nunchuck_init()
{
Wire.begin(); // join i2c bus as master
Wire.beginTransmission(0x52); // transmit to device 0x52
Wire.send(0x40); // sends memory address
Wire.send(0x00); // sends sent a zero.
Wire.endTransmission(); // stop transmitting
}
// Send a request for data to the nunchuck
// was "send_zero()"
void nunchuck_send_request()
{
Wire.beginTransmission(0x52); // transmit to device 0x52
Wire.send(0x00); // sends one byte
Wire.endTransmission(); // stop transmitting
}
// Receive data back from the nunchuck,
// returns 1 on successful read. returns 0 on failure
int nunchuck_get_data()
{
int cnt=0;
Wire.requestFrom (0x52, 6); // request data from nunchuck
while (Wire.available ()) {
// receive byte as an integer
nunchuck_buf[cnt] = nunchuk_decode_byte(Wire.receive());
cnt++;
}
nunchuck_send_request(); // send request for next data payload
// If we recieved the 6 bytes, then go print them
if (cnt >= 5) {
return 1; // success
}
return 0; //failure
}
// Print the input data we have recieved
// accel data is 10 bits long
// so we read 8 bits, then we have to add
// on the last 2 bits. That is why I
// multiply them by 2 * 2
void nunchuck_print_data()
{
static int i=0;
int joy_x_axis = nunchuck_buf[0];
int joy_y_axis = nunchuck_buf[1];
int accel_x_axis = nunchuck_buf[2]; // * 2 * 2;
int accel_y_axis = nunchuck_buf[3]; // * 2 * 2;
int accel_z_axis = nunchuck_buf[4]; // * 2 * 2;
int z_button = 0;
int c_button = 0;
// byte nunchuck_buf[5] contains bits for z and c buttons
// it also contains the least significant bits for the accelerometer data
// so we have to check each bit of byte outbuf[5]
if ((nunchuck_buf[5] >> 0) & 1)
z_button = 1;
if ((nunchuck_buf[5] >> 1) & 1)
c_button = 1;
if ((nunchuck_buf[5] >> 2) & 1)
accel_x_axis += 2;
if ((nunchuck_buf[5] >> 3) & 1)
accel_x_axis += 1;
if ((nunchuck_buf[5] >> 4) & 1)
accel_y_axis += 2;
if ((nunchuck_buf[5] >> 5) & 1)
accel_y_axis += 1;
if ((nunchuck_buf[5] >> 6) & 1)
accel_z_axis += 2;
if ((nunchuck_buf[5] >> 7) & 1)
accel_z_axis += 1;
Serial.print(i,DEC);
Serial.print("\t");
Serial.print("joy:");
Serial.print(joy_x_axis,DEC);
Serial.print(",");
Serial.print(joy_y_axis, DEC);
Serial.print(" \t");
Serial.print("acc:");
Serial.print(accel_x_axis, DEC);
Serial.print(",");
Serial.print(accel_y_axis, DEC);
Serial.print(",");
Serial.print(accel_z_axis, DEC);
Serial.print("\t");
Serial.print("but:");
Serial.print(z_button, DEC);
Serial.print(",");
Serial.print(c_button, DEC);
Serial.print("\r\n"); // newline
i++;
}
// Encode data to format that most wiimote drivers except
// only needed if you use one of the regular wiimote drivers
char nunchuk_decode_byte (char x)
{
x = (x ^ 0x17) + 0x17;
return x;
}
// returns zbutton state: 1=pressed, 0=notpressed
int nunchuck_zbutton()
{
return ((nunchuck_buf[5] >> 0) & 1) ? 0 : 1; // voodoo
}
// returns zbutton state: 1=pressed, 0=notpressed
int nunchuck_cbutton()
{
return ((nunchuck_buf[5] >> 1) & 1) ? 0 : 1; // voodoo
}
// returns value of x-axis joystick
int nunchuck_joyx()
{
return nunchuck_buf[0];
}
// returns value of y-axis joystick
int nunchuck_joyy()
{
return nunchuck_buf[1];
}
// returns value of x-axis accelerometer
int nunchuck_accelx()
{
return nunchuck_buf[2]; // FIXME: this leaves out 2-bits of the data
}
// returns value of y-axis accelerometer
int nunchuck_accely()
{
return nunchuck_buf[3]; // FIXME: this leaves out 2-bits of the data
}
// returns value of z-axis accelerometer
int nunchuck_accelz()
{
return nunchuck_buf[4]; // FIXME: this leaves out 2-bits of the data
}
When I write, Serial.Println("End"), in the line after Wire.endTransmission(); in function nunchuck_init(), it does not display on Serial Monitor.
Also, it does not display Nunchuck ready on Serial Monitor since it is written after nunchuck_init() has been called.
I am working on Arduino 0023, Windows 7.
A existing problem with the stock Arduino Wire library is that there is no timeout.
It is possible for the endTransmission function to hang the microcontroller in different scenarios.
This issue has been discussed in several other forums, and the best solution I've found so far is to use an alternate library.
The Arduino I2C Master Library by Wayne Truchsess
http://www.dsscircuits.com/index.php/articles/66-arduino-i2c-master-library
With proper timeout, it fixed the problem on my system reading the MMA7455 accelero
In the source code provided, there's an example where it shows how the same piece of program is done using Wire vs the I2C Master Library.
You can use that example to easily modify your code to adopt the new library.
I want to read the switches next to the LEDS and cycle the LEDS from 0 to whichever switch is pressed
if none are pressed cycle through all of them with the delay.For this i have used timer0. Since I work on
atmega8515. I used INT0.
Here is my implementation:
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#define BIT(n) (1 << n)
volatile uint8_t led, k, switches, i , j = 1;
/* uint8_t is the same as unsigned char */
int main(void)
{
DDRB = 0xff; /* use all pins on PortB for output */
led = 1; /* init variable representing the LED state */
PORTB = 0XFF;
cli( );
TCCR0|=(1<<CS02) |(1<<CS00);
//Enable Overflow Interrupt Enable
TIMSK|=(1<<TOIE0);
//Initialize Counter
TCNT0=0;
GICR = BIT(INT0);
MCUCR = BIT(ISC01) | BIT(ISC00);
sei( );
for ( ; ;);
}
ISR(TIMER0_OVF_vect)
{
if(switches == 0xff)
{
PORTB = ~led; /* invert the output since a zero means: LED on */
led <<= 1; /* move to next LED */
if (!led) /* overflow: start with Pin B0 again */
{
led = 1;
}
}
else
{
for (k = 0; k< 8;k++)
{
j = switches & (1 << k);
if(j == 0)
{
for(i=1;i<=(k +1);i++)
{
j = 1;
PORTB = ~j;
j = 1 << i;
_delay_ms(100); //without this delay it doesnt cycle the LEDS from to whichever switch is pressed
}
}
}
}
But using delay loops in ISR is a bad programming practice. How to use the same timer instead of the delay?
I think in the ISR, you should just update the LED status and in the main loop you could set the PORTB and read the switches values. In your code, it seems occupy so much time in ISR.