0% found this document useful (0 votes)
21 views

OSLAB

The document contains code to initialize an MPU6050 accelerometer and gyroscope sensor over I2C. It defines functions to write, read bytes, and read the accelerometer and gyroscope data. The main function initializes the sensor, then reads the accelerometer and gyroscope data in a loop and calculates the acceleration and angular velocity from the raw sensor values.

Uploaded by

楊承晞
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

OSLAB

The document contains code to initialize an MPU6050 accelerometer and gyroscope sensor over I2C. It defines functions to write, read bytes, and read the accelerometer and gyroscope data. The main function initializes the sensor, then reads the accelerometer and gyroscope data in a loop and calculates the acceleration and angular velocity from the raw sensor values.

Uploaded by

楊承晞
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

#include "mbed.

h"

DigitalIn mypin(BUTTON1);
DigitalOut led_g(LED1);
DigitalOut led_b(LED2);
DigitalOut led_r(LED3);

// main() runs in its own thread in the OS


int main()
{
if(mypin.is_connected()){
printf("mypin in initialized and connected!\n\r");
}

mypin.mode(PullNone);

while (true) {
if( mypin.read() == 1){
printf("mypin has value : %d \n\r", mypin.read());
led_g = 1;
ThisThread::sleep_for(100);
led_g = !led_g;
ThisThread::sleep_for(100);
led_b = !led_g;
ThisThread::sleep_for(100);
led_b = !led_b;
ThisThread::sleep_for(100);
led_r = !led_b;
ThisThread::sleep_for(100);
led_r = !led_r;
}else{
printf("mypin has value : %d \n\r", mypin.read());
led_r = 1;
ThisThread::sleep_for(100);
led_r = !led_r;
ThisThread::sleep_for(100);
led_b = !led_r;
ThisThread::sleep_for(100);
led_b = !led_b;
ThisThread::sleep_for(100);
led_g = !led_b;
ThisThread::sleep_for(100);
led_g = !led_g;
}
ThisThread::sleep_for(100);
}
}
#include "mbed.h"

volatile bool running = true;

void blink(DigitalOut *led){


*led = !*led;

printf("I am worker , I am waiting for taking a break.\n\r");


while(running){
printf("Turn on!\n\r");
ThisThread::sleep_for(1000);
}

printf("Turn off!\n\n\n\n\r");
*led = !*led;
}

// main() runs in its own thread in the OS


int main()
{
while(1){
Thread thread;
DigitalOut led1(LED2);
ThisThread::sleep_for(1s);
printf("I am boss, I am ready.\n\r");
printf("All workers, work now.\n\r");
thread.start(callback(blink, &led1));

ThisThread::sleep_for(5s);

running = false;

printf("All workers, take a break now.\n\r");


thread.join();

running = true;
}
}
#include "mbed.h"
#include <cstdint>

#define MAXIMUM_BUFFER_SIZE 32

static BufferedSerial serial_port(USBTX, USBRX);


static DigitalOut led1(LED1);
static DigitalOut led2(LED2);
static DigitalOut led3(LED3);

// main() runs in its own thread in the OS


int main()
{
serial_port.set_baud(9600);
serial_port.set_format(8, BufferedSerial::None, 1);

uint32_t flag = 1;
char buf[MAXIMUM_BUFFER_SIZE] = {0};

while (true) {
if(uint32_t num = serial_port.read(buf, sizeof(buf))){
if(flag==1){
if(buf[0] == 49){
led1 = 1;
}
else if(buf[0] == 48){
led1 = 0;
}
flag = 2;
}
else if(flag==2){
if(buf[0] == 49){
led2 = 1;
}
else if(buf[0] == 48){
led2 = 0;
}
flag = 3;
}
else if(flag==3){
if(buf[0] == 49){
led3 = 1;
}
else if(buf[0] == 48){
led3 = 0;
}
flag = 1;
}
serial_port.write(buf, num);
}
}
}
#include "mbed.h"
#include <cstdint>

typedef struct{
uint32_t a;
uint32_t b;
uint32_t c;
} message_t;

DigitalIn mypin(BUTTON1);
MemoryPool<message_t, 16> mpool;
Queue<message_t, 16> queue;
Thread thread;

void send_thread(void){
uint32_t i=0, count=0;
uint32_t j=0;
scanf("%u", &i);
j = i;
while(j>0){
count++;
j=j/10;
}
while(true){
message_t *message = mpool.alloc();
message->a = i/pow(10, count-1);
message->b = (i-message->a*pow(10, count-1))/pow(10, count-2);
message->c = message->a + message->b;
i = i-message->a*pow(10, count-1)-message->b*pow(10, count-2);
if(count!=0){
count = count-2;
}

queue.put(message);
ThisThread::sleep_for(1000);
}
}

// main() runs in its own thread in the OS


int main()
{
thread.start(callback(send_thread));
while (true) {
osEvent evt = queue.get();
if (evt.status == osEventMessage){
while(mypin){

}
message_t *message = (message_t *)evt.value.p;
printf("\nSummand: %u \n\r", message->a);
printf("Addend: %u \n\r", message->b);
printf("Sum: %u\n\r", message->c);
mpool.free(message);
ThisThread::sleep_for(200);
}
}
}
#include "mbed.h"

InterruptIn alarm(BUTTON1);
DigitalOut led_g(LED1);
DigitalOut led_r(LED3);

void trigger_isr(){
alarm.disable_irq();
led_g = !led_g;
}

int main()
{
led_r = 1;
led_g = 0;
alarm.rise(&trigger_isr);
while (true) {
alarm.enable_irq();
led_r = !led_r;
ThisThread::sleep_for(500ms);
}
}
#include "mbed.h"

InterruptIn alarm(BUTTON1);
DigitalOut led1(LED1);
DigitalOut led2(LED2);
DigitalOut led3(LED3);
DigitalOut pin_1(D15);
volatile int _count;

int prime(int n){


if (n == 0 || n == 1)
return 0;

for (int i = 2; i <= n / 2; ++i) {


// if n is divisible by i, then n is not prime
// change flag to 1 for non-prime number
if (n % i == 0) {
return 0;
}
}
return 1;
}

void trigger_isr(){
alarm.disable_irq();
_count++;
int j = _count % 8;
led1 = j / 4;
led2 = (j % 4) / 2;
led3 = j % 2;
}

void th(){
if(prime(_count)==1){
pin_1 = 0;
}
else if(prime(_count)==0){
pin_1 = 1;
}
}

void hehe(){
printf("Button pressed!\n");
printf("Count:%d\n",_count);
if(prime(_count)==1){
printf("Count is prime, motor stop running\n");
}
else if(prime(_count)==0){
printf("Count is not prime, motor running\n");
}
}

int main()
{
pin_1 = 0;
int count = _count;
alarm.rise(&trigger_isr);
while(1){
Thread thread;
if(count != _count){
thread.start(callback(th));
hehe();
count = _count;
}
alarm.enable_irq();
ThisThread::sleep_for(500ms);
}
}
#include "mbed.h"

Mutex stdio_mutex;
Thread thread1;
Thread thread2;
Thread thread3;
DigitalOut led3(LED3);

void notify(const char *name, int state){


stdio_mutex.lock();
led3 = 0;
printf("%s: %d\n\r", name, state);
led3 = 1;
stdio_mutex.unlock();
}

void test_thread(void const *args){


for(int i=1; i<11; i++){
notify((const char *)args, i);
ThisThread::sleep_for(1000);
if(i==5){
printf("Take a break!\n");
ThisThread::sleep_for(5000);
}
}

// main() runs in its own thread in the OS


int main()
{
thread2.start(callback(test_thread, (void *)"Thread 2"));
thread3.start(callback(test_thread, (void *)"Thread 3"));

test_thread((void *)"Thread 1");

thread1.join();
thread2.join();
thread3.join();

}
#include "mbed.h"
#include "ADXL345.h"

// main() runs in its own thread in the OS


DigitalOut led3(LED3);
Mutex stdio_mutex;
ADXL345 accelerometer( PA_7, PA_6, PA_5, PA_2);

int main()
{
int readings[3] = {100, 100, 100};
int store[10][3];
int count = 0;
led3 = 0;

accelerometer.setPowerControl(0x00);
accelerometer.setDataFormatControl(0x0B);
accelerometer.setDataRate(ADXL345_3200HZ);
accelerometer.setPowerControl(0x08);

while (true) {
count++;
printf("Collected 嚗?i%%\n", count*10);

stdio_mutex.lock();
led3 = !led3;
ThisThread::sleep_for(500ms);
led3 = !led3;
ThisThread::sleep_for(500ms);
stdio_mutex.unlock();

accelerometer.getOutput(readings);

store[count][0] = (int16_t)readings[0];
store[count][1] = (int16_t)readings[1];
store[count][2] = (int16_t)readings[2];
if(count >= 10){
break;
}
}

led3 = 0;

for(int i=1; i<=10; i++){


printf("Data %i 嚗?i, %i, %i\n", i, store[i][0], store[i][1], store[i][2]);
}

}
#include "mbed.h"
#include <cstdint>

Semaphore semaphore1(1);
Semaphore semaphore2(0);
Semaphore semaphore3(0);
DigitalOut led3(LED3);

Thread t2;
Thread t3;
uint16_t i=1;

void test_thread1(void const *name){


while(true){
semaphore1.acquire();
led3 = !led3;
printf("蝚?02d 甈?%s\n\r", i, (const char*)name);
semaphore2.release();
if(i==10) break;
}
}
void test_thread2(void const *name){
while(true){
semaphore2.acquire();
printf("%s\n\r", (const char*)name);
semaphore3.release();
if(i==10) break;
}
}
void test_thread3(void const *name){
while(true){
semaphore3.acquire();
printf("%s\n\r", (const char*)name);
led3 = !led3;
ThisThread::sleep_for(1s);
semaphore1.release();
if(i==10) break;
i++;
}
}

// main() runs in its own thread in the OS


int main()
{
t2.start(callback(test_thread2, (void *)"B"));
t3.start(callback(test_thread3, (void *)"C"));

test_thread1((void *)"A");
}
#include "mbed.h"
#include "LCDi2c.h"
#include "mpu6050Reg.h"
#include <cstdint>

DigitalOut led1(LED1);
DigitalOut led2(LED2);
DigitalOut led3(LED3);
I2C i2c(I2C_SDA, I2C_SCL);

LCDi2c lcd(A4, A5);

enum Ascale{
AFS_2G = 0, AFS_4G, AFS_8G, AFS_16G
};

enum Gscale{
GFS_250DPS = 0, GFS_500DPS, GFS_1000DPS, GFS_2000DPS
};

void writeByte(uint8_t address, uint8_t subAddress, uint8_t data);


char readByte(uint8_t address, uint8_t subAddress);
void readBytes(uint8_t address, uint8_t subAddress, uint8_t count, uint8_t *dest);

void initMPU6050();
void readAccelData(int16_t * destination);
void readGyroData(int16_t * destination);

// main() runs in its own thread in the OS


int main()
{
const float Accel_sensitivity = 16384.0;
const float Gyro_sensitivity = 131.0;
int16_t Accel_raw_data[3] = {0,0,0};
int16_t Gyro_raw_data[3] = {0,0,0};
float Ax,Ay,Az,Gx,Gy,Gz;

Ax=Ay=Az=Gx=Gy=Gz;
initMPU6050();

while (true) {
readAccelData(Accel_raw_data);
readGyroData(Gyro_raw_data);

Ax = float(Accel_raw_data[0]) / Accel_sensitivity;
Ay = float(Accel_raw_data[1]) / Accel_sensitivity;
Az = float(Accel_raw_data[2]) / Accel_sensitivity;

Gx = Gyro_raw_data[0] / Gyro_sensitivity;
Gy = Gyro_raw_data[1] / Gyro_sensitivity;
Gz = Gyro_raw_data[2] / Gyro_sensitivity;

printf("--Ax 嚗?%.2f g,Ay 嚗?%.2f g,Az 嚗?%.2f g --\n",Ax,Ay,Az);


printf("\n--Gx 嚗?%.2f,Gy 嚗?%.2f,Gz 嚗?%.2f --\n",Gx,Gy,Gz);
ThisThread::sleep_for(1000ms);

lcd.locate(0,0);
lcd.printf(" 4109064233 ");

}
}

void writeByte(uint8_t address, uint8_t subAddress, uint8_t data){


char data_write[2];
data_write[0] = subAddress;
data_write[1] = data;
i2c.write(address, data_write, 2, 0);
}

char readByte(uint8_t address, uint8_t subAddress){


char data[1];
char data_write[1];
data_write[0] = subAddress;
i2c.write(address, data_write, 1, 1);

i2c.read(address, data, 1, 0);


return data[0];
}

void readBytes(uint8_t address, uint8_t subAddress, uint8_t count, uint8_t *dest){


char data[14];
char data_write[1];
data_write[0] = subAddress;
i2c.write(address, data_write,1 ,1);
i2c.read(address, data, count, 0);
for(int i=0; i<count; i++){
dest[i] = data[i];
}
}

void initMPU6050(){
int Gscale = GFS_250DPS;
int Ascale = AFS_2G;

writeByte(MPU6050_ADDRESS, PWR_MGMT_1, 0x00);


ThisThread::sleep_for(100ms);

writeByte(MPU6050_ADDRESS, PWR_MGMT_1, 0x01);


writeByte(MPU6050_ADDRESS, CONFIG, 0x03);

writeByte(MPU6050_ADDRESS, SMPLRT_DIV, 0x04);

uint8_t data = readByte(MPU6050_ADDRESS, GYRO_CONFIG);


writeByte(MPU6050_ADDRESS, GYRO_CONFIG, data | Gscale << 3);

data = readByte(MPU6050_ADDRESS, ACCEL_CONFIG);


writeByte(MPU6050_ADDRESS, ACCEL_CONFIG, data | Ascale << 3);
}

void readAccelData(int16_t *target){


uint8_t rawData[6] = {0,0,0,0,0,0};
uint8_t count = 6;
readBytes(MPU6050_ADDRESS, ACCEL_XOUT_H, count, rawData);
///
target[0] = int16_t(rawData[0] << 8) + rawData[1];
target[1] = int16_t(rawData[2] << 8) + rawData[3];
target[2] = int16_t(rawData[4] << 8) + rawData[5];
///
}

void readGyroData(int16_t * target){


uint8_t rawData[6] = {0,0,0,0,0,0};
uint8_t count = 6;
readBytes(MPU6050_ADDRESS, GYRO_XOUT_H, count, rawData);
///
target[0] = int16_t(rawData[0] << 8) + rawData[1];
target[1] = int16_t(rawData[2] << 8) + rawData[3];
target[2] = int16_t(rawData[4] << 8) + rawData[5];
///
}
#include "mbed.h"
#include <cstdint>
#include <cstdio>
#define SAMPLE_INTERVAL 100000

DigitalOut led1(LED1);
DigitalOut led2(LED2);
DigitalOut led3(LED3);

Thread t;
Timer watch;

void test_thread(){
watch.start();
led1 = 1;
while (true) {
if(watch.read()>=12){
led3 = 0;
led1 = 1;
watch.reset();
}
else if(watch.read()>=7){
led2 = 0;
led3 = 1;
}
else if(watch.read()>=5){
led1 = 0;
led2 = 1;
}
ThisThread::sleep_for(1ms);
}
}
// main() runs in its own thread in the OS
int main()
{
t.start(callback(test_thread));
}
#include "mbed.h"

AnalogIn ain(A0);
DigitalOut dout1(LED1);
DigitalOut dout2(LED2);
DigitalOut dout3(A1);

// main() runs in its own thread in the OS


int main()
{
float V;
while (true) {
V = 3.5*ain.read();
dout1 = V;
dout2 = V/2;
dout3 = V/3;

printf("voltage: %.3f\n", V);


ThisThread::sleep_for(200);
}
}
#include "mbed.h"

EventQueue queue;
void handler(int count);
Event<void(int)> event1(&queue, handler);
Event<void(int)> event2(&queue, handler);

void handler(int count)


{
unsigned time_ms = equeue_tick();
printf("Timestamp = %d Event = %d \n", time_ms, count);
return;
}

void post_events(void)
{

event1.post(1);
event1.post(2);
event1.post(3);

event1.cancel();

event1.post(4);

event2.post(5);

int main()
{
Thread event_thread;

event1.delay(100ms);
event1.period(200ms);

event2.delay(400ms);
event2.period(non_periodic);

event_thread.start(callback(post_events));

queue.dispatch(800);

event_thread.join();

}
#include "mbed.h"

PwmOut motor(D15);

int main()
{
motor.period(4.0f);
motor.write(0.50f);
}
#include "mbed.h"
#include <cstdint>

#define SAMPLE_FLAG1 (1UL << 0)


#define SAMPLE_FLAG2 (1UL << 1)

Mutex mutex;
ConditionVariable c_pro(mutex);
ConditionVariable c_con(mutex);

InterruptIn button(BUTTON1);

EventFlags event_flags;

Thread p;
Thread c;

uint32_t _counter = 0;
uint32_t product_count = 0;
uint32_t consume_count = 0;
uint32_t buffer = 10;

bool done = false;

void producer_thread(){

while(1){
mutex.lock();

if(_counter<buffer){
_counter++;
if(_counter==1){
c_con.notify_one();
}
product_count++;
printf("Produced: %d, Buffer_count: %d\r\n", product_count, _counter);
}
else{
printf("Buffer is full, waiting for consumers to buy!\r\n");
c_pro.wait();
}
mutex.unlock();
ThisThread::sleep_for(2s);
}

void consumer_thread(){
while(1){
event_flags.wait_any(SAMPLE_FLAG2);
event_flags.set(SAMPLE_FLAG1);
mutex.lock();

if(_counter>0){
_counter--;
if(_counter<10){
c_pro.notify_one();
}
consume_count++;
printf("Consumed: %d, Buffer_count: %d\r\n", consume_count, _counter);
}
else{
printf("Please wait!\r\n");
c_con.wait();
}
mutex.unlock();
ThisThread::sleep_for(500ms);

}
// main() runs in its own thread in the OS
int main()
{
p.start(producer_thread);
c.start(consumer_thread);
while(true){
if(!button){
event_flags.set(SAMPLE_FLAG2);
}
ThisThread::sleep_for(200ms);
}
}
#include "mbed.h"
#include "MQTTClientMbedOs.h"
#include <cstdio>
#include <cstring>
#include <string>
#include <iostream>
using namespace std;

//Define the maximum search capacity of wifiAP


static constexpr size_t MAX_NUMBER_OF_ACCESS_POINTS = 10;
static constexpr size_t MAX_MESSAGE_RECEIVED_LENGTH = 100;
static constexpr size_t REMOTE_PORT = 1883;
const char *pub_topic = "pub_msg/topic";
const char *sub_topic = "sub_msg/topic";
const char* clientID = "Group 14";
const char *TOPIC = "OSLab/Group14";

DigitalIn button(BUTTON1);
DigitalOut led1(LED1);
DigitalOut led2(LED2);
DigitalOut led3(LED3);

class Mqtt_App
{

public:
Mqtt_App() : _net(NetworkInterface::get_default_instance()) {}
~Mqtt_App()
{
if(_net)
{
_net->disconnect();
}
}

void run()
{
if(!_net)
{
printf("[Error] No network interface found.\r\n");
return;
}
//Search available wifi.
if(_net->wifiInterface())
{
wifi_scan();
}
// Connecting to Wifi (Depend on mbed_app.json)
printf("\nConnecting to the network...\r\n");

nsapi_size_or_error_t result = _net->connect();


if (result != 0)
{
printf("[Error] Failed connect Network : _net->connect() returned: %d\r\n",
result);
return;
}

SocketAddress addr;
_net->get_ip_address(&addr);
printf("[Success] connected to wifi , IP address : %s\r\n", addr.get_ip_address());

// Setting broker address and Connect


printf("\nConnecting to the socket ...\r\n");

SocketAddress address;
_net->gethostbyname(MBED_CONF_APP_HOSTNAME, &address);
address.set_port(REMOTE_PORT);
_socket.open(_net);
nsapi_size_or_error_t socket_result = _socket.connect(address);
if(socket_result != 0)
{
printf("[Error] Failed connect Socket : _socket.connect() returned: %d\r\n",
socket_result);
return;
}
printf("[Success] connected to Socket.\n");
printf("\nConnecting to the MQTT Broker ...\r\n");
//Trying to use Mqtt to connect to broker to send messages and receive
messages
MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
data.clientID.cstring = (char *)clientID;
data.username.cstring = (char *)MBED_CONF_MBED_MQTT_TESTS_USERNAME;
data.password.cstring = (char *)MBED_CONF_MBED_MQTT_TESTS_PASSWORD;
// Connect MQTT with data through the socket
MQTTClient client(&_socket);
nsapi_size_or_error_t mqtt_result = client.connect(data);
if(mqtt_result != 0)
{
printf("[Error] Failed MQTT Connection : client.connect() returned: %d\r\n",
mqtt_result);
return;
}
printf("[Success] connected to MQTT Broker.\n");

// Trying publish message to pub_topic


const char* mes = "NCHU_OSLab_Group_14";
MQTT::Message message2 =
{
.qos = MQTT::QoS::QOS2,
.retained = false,
.dup = false,
.id = 0,
.payload = (void*)mes,
.payloadlen = strlen(mes)
};
printf("[Publish] Topic : %s, Message : %s\r\n",pub_topic,mes);
client.subscribe(sub_topic, MQTT::QOS2, message_arrived);
while(true)
{
ThisThread::sleep_for(50ms);
client.yield(100);

if(button==0){
printf("Send message~\n");
client.publish(TOPIC, message2);
}

}
}
private:
void wifi_scan()
{
WiFiInterface *wifi = _net->wifiInterface();
WiFiAccessPoint ap[MAX_NUMBER_OF_ACCESS_POINTS];
int result = wifi->scan(ap, MAX_NUMBER_OF_ACCESS_POINTS);
if(result <= 0)
{
printf("WiFiInterface::scan() failed with return value : %d\r\n", result);
return;
}
printf("%d networks available:\r\n",result);
for(int i = 0; i < result; i++)
{
printf("Network: %s BSSID: %hhX:%hhX:%hhX:%hhx:%hhx:%hhx\r\n",
ap[i].get_ssid(),
ap[i].get_bssid()[0], ap[i].get_bssid()[1], ap[i].get_bssid()[2],
ap[i].get_bssid()[3], ap[i].get_bssid()[4], ap[i].get_bssid()[5]);
}
}
static void message_arrived(MQTT::MessageData &md)
{
char messages[10];
printf("\n--------------------Message arrived--------------------\n");
printf("[Subscribe] Topic : %.*s, Message : %.*s\n\n",
md.topicName.lenstring.len, md.topicName.lenstring.data,
static_cast<int>(md.message.payloadlen),
static_cast<char *>(md.message.payload));
sprintf(messages, "%.*s", static_cast<int>(md.message.payloadlen),
static_cast<char *>(md.message.payload));
if(strcmp(messages, "Red_On") == 0){
led3 = 1;
}
if(strcmp(messages, "Green_On") == 0){
led2 = 1;
}
if(strcmp(messages, "Close") == 0){
led2 = 0;
led3 = 0;
}
printf("\n-------------------------------------------------------\n");
}
private:
NetworkInterface *_net;
TCPSocket _socket;
};

int main()
{
Thread thread;

Mqtt_App *app = new Mqtt_App();


MBED_ASSERT(app);
thread.start(callback(app, &Mqtt_App::run));

while (true)
{
ThisThread::sleep_for(50ms);
}
return 0;
}

You might also like