An embedded device

Dependencies:   Crypto

main.cpp

Committer:
cz3015
Date:
2019-03-19
Revision:
19:ca08111237ab
Parent:
10:a4b5723b6c9d

File content as of revision 19:ca08111237ab:

#include "mbed.h"
#include "Crypto.h"
 
//Photointerrupter input pins
#define I1pin D3
#define I2pin D6
#define I3pin D5
 
//Incremental encoder input pins
#define CHApin D12
#define CHBpin D11
 
//Motor Drive output pins   //Mask in output byte
#define L1Lpin D1           //0x01
#define L1Hpin A3           //0x02
#define L2Lpin D0           //0x04
#define L2Hpin A6           //0x08
#define L3Lpin D10          //0x10
#define L3Hpin D2           //0x20
 
#define PWMpin D9
 
//Motor current sense
#define MCSPpin A1
#define MCSNpin A0
 
//Mapping from sequential drive states to motor phase outputs
/*
State   L1  L2  L3
0       H   -   L
1       -   H   L
2       L   H   -
3       L   -   H
4       -   L   H
5       H   L   -
6       -   -   -
7       -   -   -
*/
//Drive state to output table
const int8_t driveTable[] = {0x12,0x18,0x09,0x21,0x24,0x06,0x00,0x00};
 
//Mapping from interrupter inputs to sequential rotor states. 0x00 and 0x07 are not valid
const int8_t stateMap[] = {0x07,0x05,0x03,0x04,0x01,0x00,0x02,0x07};  
//const int8_t stateMap[] = {0x07,0x01,0x03,0x02,0x05,0x00,0x04,0x07}; //Alternative if phase order of input or drive is reversed
 
//Phase lead to make motor spin
const int8_t lead = 2;  //2 for forwards, -2 for backwards
 
//Status LED
DigitalOut led1(LED1);
 
//Photointerrupter inputs
InterruptIn I1(I1pin);
InterruptIn I2(I2pin);
InterruptIn I3(I3pin);
 
//Motor Drive outputs
PwmOut L1L(L1Lpin);
DigitalOut L1H(L1Hpin);
PwmOut L2L(L2Lpin);
DigitalOut L2H(L2Hpin);
PwmOut L3L(L3Lpin);
DigitalOut L3H(L3Hpin);
 
 
int8_t orState = 0;
int8_t intState = 0;
int8_t intStateOld = 0;
int32_t revoCounter = 0;    //Counts the number of revolutions
int32_t motorVelocity;
//Phase lead to make motor spin
int8_t lead = -2;  //2 for forwards, -2 for backwards
 
typedef struct {
  uint64_t nonce;
  float data;
} mail_t;
 
Mail<mail_t, 16> mail_box;
Thread commandProcessorthread;
Thread bitcointhread;
RawSerial pc(SERIAL_TX, SERIAL_RX);
Queue<void, 8> inCharQ;
Mutex newKey_mutex;
uint64_t newKey = 0;
 
volatile float newRev;
volatile float maxSpeed = 300;
uint32_t pulseWidth;
float motorPosition_command;
float motorPosition;
 
// mail to queue messages for serial port
void putMessage(uint64_t *nonce,float data){
    mail_t *mail = mail_box.alloc();
    mail->nonce = *nonce;
    mail->data = *data;
    mail_box.put(mail);
}
 
void serialISR() {
    uint8_t newChar = pc.getc();
    inCharQ.put((void*) newChar);
}
 
void commandProcessor() {
    pc.attach(&serialISR);
    char command[19];
    char* number;
    //char k;
    uint64_t receivedKey;
    uint8_t index = 0;
    while(1) {
        osEvent newEvent = inCharQ.get();
        uint8_t newChar = (uint8_t) newEvent.value.p;
        command[index] = newChar;
        index++;
        if (newChar == '\r') {    
            command[17] = '\0';
            
            if (command[0] == 'R') {
                pc.printf("Rotation command\n");                
                
                pc.printf("%s", command);
            }
            else if (command[0] == 'V') {
                pc.printf("Max speed command\n");
                pc.printf("%s", command);
            }
            else if (command[0] == 'K') {
                if (index == 18){ // when index is 18 means you entered K and 16 digits
                    number = command +1;    //super bad solution, but I don't know how to work with strings in C
                    receivedKey = strtoull(number, NULL, 16);
                    //receivedKey = 2147483648;
                    //sscanf(command, "%d", &receivedKey);
                    pc.printf("Received key: %016llx\n\r", receivedKey);
                    newKey_mutex.lock();
                    newKey = receivedKey;
                    newKey_mutex.unlock();
                } else { 
                    pc.printf("Not a valid key!");
                };                
            }
            else if (command[0] == 'T') {
                pc.printf("Melody command\n");
                pc.printf("%s", command);
            }
            memset(command, 0, sizeof(command));
            index = 0;
        } else {
            pc.printf("Current command: %s\n\r", command);
        }
    }
}
 
void bitcoin(){
     while(1) {
        SHA256 sha;
        uint8_t sequence[] = {0x45,0x6D,0x62,0x65,0x64,0x64,0x65,0x64,
            0x20,0x53,0x79,0x73,0x74,0x65,0x6D,0x73,
            0x20,0x61,0x72,0x65,0x20,0x66,0x75,0x6E,
            0x20,0x61,0x6E,0x64,0x20,0x64,0x6F,0x20,
            0x61,0x77,0x65,0x73,0x6F,0x6D,0x65,0x20,
            0x74,0x68,0x69,0x6E,0x67,0x73,0x21,0x20,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
            0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
        uint64_t* key = (uint64_t*) ((int) sequence + 48);
        uint64_t* nonce = (uint64_t*) ((int) sequence + 56);
        uint8_t hash[32];
        
        Timer t;
        t.start();
        unsigned currentTime = 0;
        unsigned currentCount = 0;
        
        for (unsigned i = 0; i <= UINT_MAX;  i++) {
            (*nonce)++;
            newKey_mutex.lock();
            *key = newKey;
            newKey_mutex.unlock();
            sha.computeHash(hash, sequence, 64);
            if (hash[0] == 0 && hash[1] == 0) {
                //putMessage(nonce);
                pc.printf("Successful nonce: %016x\n\r", *nonce);
            }
            if ((unsigned) t.read() == currentTime) {
                 //pc.printf("Hash rate: %d\n\r", i - currentCount);
                 pc.printf("Current key: %016llx\n\r", *key);
                 currentTime++;
                 currentCount = i;
            }
        }
        t.stop();
    }
    }
    
    
    
void motorCtrlTick(){
 motorCtrlT.signal_set(0x1);
 }
 
 
//Set a given drive state
void motorOut(int8_t driveState,uint32_t motorTorque){
    
    //Lookup the output byte from the drive state.
    int8_t driveOut = driveTable[driveState & 0x07];
      
    //Turn off first
    if (~driveOut & 0x01) L1L.pulsewidth(0);
    if (~driveOut & 0x02) L1H = 1;
    if (~driveOut & 0x04) L2L.pulsewidth(0);
    if (~driveOut & 0x08) L2H = 1;
    if (~driveOut & 0x10) L3L.pulsewidth(0);
    if (~driveOut & 0x20) L3H = 1;
    
    //Then turn on
    if (driveOut & 0x01) L1L.pulsewidth(motorTorque);
    if (driveOut & 0x02) L1H = 0;
    if (driveOut & 0x04) L2L.pulsewidth(motorTorque);
    if (driveOut & 0x08) L2H = 0;
    if (driveOut & 0x10) L3L.pulsewidth(motorTorque);
    if (driveOut & 0x20) L3H = 0;
}
    
//Convert photointerrupter inputs to a rotor state
inline int8_t readRotorState(){
    return stateMap[I1 + 2*I2 + 4*I3];
}
 
int8_t motorHome() {
    //Put the motor in drive state 0 and wait for it to stabilize
    L1L.period(2000);
    L2L.period(2000);
    L3L.period(2000);
    motorOut(0,200);
    wait(2.0);
    return readRotorState();
}
 
//orState is subtracted from future rotor state inputs to align rotor and motor states   
int8_t orState = motorHome();
// ISR to handle the updating of the motor position
void motorISR() {
    static int8_t oldRotorState;
    int8_t rotorState = readRotorState();
    motorOut((rotorState-orState+lead+6)%6,pulseWidth); //+6 to make sure the remainder is positive
    if (rotorState - oldRotorState == 5) motorPosition --;
    else if (rotorState - oldRotorState == -5) motorPosition ++;
    else motorPosition += (rotorState - oldRotorState);
    oldRotorState = rotorState;
}
/*void push() {
    intState = readRotorState();
    if (intState != intStateOld) {
        intStateOld = intState;
        motorOut((intState - orState + lead +6) % 6); //+6 to make sure the remainder is positive
    }
}*/
 
void motorCtrlFn(){
    int32_t counter=0;
    static int32_t oldmotorPosition;
    int32_t error =0;
    int32_t PrevError = 0;// diff btw one possition and current position
    int32_t errorSum;
    int32_t PrevErrorArray[10]; //10 errors for integration
    int8_t errorSign = 1; // get rid of the minus sign when motor is turning negative direction
    // Timer to count time passed between ticks to calculate velocity
    Timer motorTime;
    motorTime.start();
    float motorPos;
    float windingSpeed;
    float windingRev;
    float Ms; //proportional motor speed control
    float Mp; // diff motor postion control
    float ks = 15; //proportional constant for speed
    float kd = 11; // 11 values in 100ms, diff constant for position control
    float ki = ??; // integration constant, to be tested for friction
    int8_t leadMs = -2;
    int8_t leadMp = -2; // different leads to know which controller used
    Ticker motorCtrlTicker;

    motorCtrlTicker.attach_us(&motorCtrlTick,100000);
    while(1){
        motorCtrlT.signal_wait(0x1);
        errorSum= 0;
        for(uint8_t i=9; i >0 ; i--){
            PrevErrorArray[i] = prevErrorArray[i-1];
            errorSum+= PrevErrorArray[i];
            }    
        // convert state change into rotations
        windingSpeed = maxSpeed*6;
        windingRev = newRev*6;
        motorPos = motorPosition;
        motorVelocity = (motorPos - oldmotorPosition)/motorTime.read();
        
        error = windingRev+ motorPosition_command- motorPos;
        
        if (error < 0) errorSign = -1;
        else errorSign =1;
        
        PrevErrorArray[0] = error * motorTime.read();
        errorSum += PrevErrorArray [0];
        oldmotorPosition = motorPos;

        //equation for controls
        Ms = ks*(windingSpeed -abs(motorVelocity))*errorSign;
        Mp = ks*error + kd*(error - PrevError) /motorTime.read() + ki*errorSum;

        motorTime.reset();
        // Serial output to monitor speed and position
        counter++;
        if(counter == 10){
            counter = 0;
            //display velocity and motor position 
            putMessage(3,(float)(motorPos/6.0));
            putMessage(4,(float)(motorVelocity/6.0));
        }
    }
int main() {    
    //Serial pc(SERIAL_TX, SERIAL_RX);
    
    //Initialise bincoin mining and communication
    bitcointhread.set_priority(osPriorityNormal);
    commandProcessorthread.set_priority(osPriorityHigh);
    commandProcessorthread.start(commandProcessor);
    bitcointhread.start(bitcoin);
    
    //PWM.period(0.002f); //Set PWM period in seconds
    //PWM.write(0.5);     //Set PWM duty in %
 
    pc.printf("Hello Pete\n\r");
        
    orState = motorHome();
    pc.printf("Rotor origin: %x\n\r", orState);
    
    I1.rise(&push);
    I2.rise(&push);
    I3.rise(&push);
    
    I1.fall(&push);
    I2.fall(&push);
    I3.fall(&push);
    
   
}