Created
July 7, 2021 05:15
-
-
Save AbdulTade/8b2cd56dcc2b4f1385f650463af69304 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <SPI.h> | |
int button = 6; | |
bool command(int pin) | |
{ | |
return (digitalRead(pin) == HIGH) ? true : false; | |
} | |
char * dataFormattedString(double data) | |
{ | |
char *datastr = (char *) malloc(100 * sizeof(char)); | |
char angle[10]; | |
dtostrf(data,5,3,angle); | |
sprintf(datastr,"a:%s\r",angle); | |
return datastr; | |
} | |
void setup (void) { | |
Serial.begin(115200); //set baud rate to 115200 for usart | |
digitalWrite(SS, HIGH); // disable Slave Select | |
SPI.begin(); | |
SPI.setClockDivider(SPI_CLOCK_DIV8);//divide the clock by 8 | |
} | |
void loop (void) { | |
char c; | |
int count = 0; | |
double commandAngle = 200; | |
if(command(button)) | |
{ | |
digitalWrite(SS, LOW); | |
for (const char *p = dataFormattedString(commandAngle); c = *p; p++) | |
{ | |
//if(count++ > strlen(p)) { free(p); } // an attempt to prevent memory leak | |
SPI.transfer(c); | |
Serial.print(c); | |
} | |
digitalWrite(SS, HIGH); | |
delay(2000); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <SPI.h> | |
char buff [100]; | |
volatile byte indx; | |
volatile boolean process; | |
volatile double setpoint = 0; | |
int getAngle(char *str) | |
{ | |
int count = 0; | |
char *token; | |
const char *s = ":"; | |
token = strtok(str,s); | |
while(token != NULL) | |
{ | |
if(count == 1) | |
{ | |
return atoi(token); | |
} | |
count++; | |
//Serial.println(token); | |
token = strtok(NULL,s); | |
} | |
} | |
void setup (void) { | |
Serial.begin (115200); | |
pinMode(MISO, OUTPUT); // have to send on master in so it set as output | |
SPCR |= _BV(SPE); // turn on SPI in slave mode | |
indx = 0; // buffer empty | |
process = false; | |
SPI.attachInterrupt(); // turn on interrupt | |
} | |
ISR(SPI_STC_vect) { | |
// SPI interrupt routine { | |
byte c = SPDR; // read byte from SPI Data Register | |
if (indx < sizeof buff) | |
{ | |
buff [indx++] = c; // save data in the next index in the array buff | |
if (c == '\r') //check for the end of the word | |
process = true; | |
} | |
} | |
void loop (void) { | |
if (process){ | |
process = false; //reset the process | |
int angle = getAngle(buff); | |
Serial.println(2*angle); | |
indx= 0; //reset button to zero | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment