русс | укр

Языки программирования

ПаскальСиАссемблерJavaMatlabPhpHtmlJavaScriptCSSC#DelphiТурбо Пролог

Компьютерные сетиСистемное программное обеспечениеИнформационные технологииПрограммирование

Все о программировании


Linux Unix Алгоритмические языки Аналоговые и гибридные вычислительные устройства Архитектура микроконтроллеров Введение в разработку распределенных информационных систем Введение в численные методы Дискретная математика Информационное обслуживание пользователей Информация и моделирование в управлении производством Компьютерная графика Математическое и компьютерное моделирование Моделирование Нейрокомпьютеры Проектирование программ диагностики компьютерных систем и сетей Проектирование системных программ Системы счисления Теория статистики Теория оптимизации Уроки AutoCAD 3D Уроки базы данных Access Уроки Orcad Цифровые автоматы Шпаргалки по компьютеру Шпаргалки по программированию Экспертные системы Элементы теории информации

Задание


Дата добавления: 2015-08-31; просмотров: 939; Нарушение авторских прав


1. Подключить отладочный модуль MSP430 LaunchPad с установленным в DIP-гнездо микроконтроллером MSP430G2452 при помощи кабеля к разъему порта USB компьютера. Запустить среду разработки Energia. Произвести настройку связи среды разработки Energia с отладочным модулем LaunchPad.

2. Загрузить примеры программ Blink, Button, Debonce, StateChangeDetection в среде разработки Energia. Изучить программные коды и произвести прошивку микроконтроллера для всех этих программ. Проверить экспериментально правильность работы программ на отладочном модуле LaunchPad.

/*

Blink

The basic Energia example.

Turns on an LED on for one second, then off for one second, repeatedly.

Change the LED define to blink other LEDs.

 

Hardware Required:

* LaunchPad with an LED

 

This example code is in the public domain.

*/

 

// most launchpads have a red LED

//#define LED RED_LED

 

//see pins_energia.h for more LED definitions

#define LED GREEN_LED

 

// the setup routine runs once when you press reset:

void setup() {

// initialize the digital pin as an output.

pinMode(LED, OUTPUT);

}

 

// the loop routine runs over and over again forever:

void loop() {

digitalWrite(LED, HIGH); // turn the LED on (HIGH is the voltage level)

delay(5000); // wait for a second

digitalWrite(LED, LOW); // turn the LED off by making the voltage LOW

delay(5000); // wait for a second

}

 

 

// constants won't change. They're used here to

// set pin numbers:

const int buttonPin = PUSH2; // the number of the pushbutton pin

const int ledPin = GREEN_LED; // the number of the LED pin

 

// variables will change:

int buttonState = 0; // variable for reading the pushbutton status



 

void setup() {

// initialize the LED pin as an output:

pinMode(ledPin, OUTPUT);

// initialize the pushbutton pin as an input:

pinMode(buttonPin, INPUT_PULLUP);

}

 

void loop(){

// read the state of the pushbutton value:

buttonState = digitalRead(buttonPin);

 

// check if the pushbutton is pressed.

// if it is, the buttonState is HIGH:

if (buttonState == HIGH)

{

// turn LED on:

digitalWrite(ledPin, LOW);

}

else {

// turn LED off:

digitalWrite(ledPin, HIGH);

}

}

 


 


 

// constants won't change. They're used here to

// set pin numbers:

const int buttonPin = PUSH2; // the number of the pushbutton pin

const int ledPin = GREEN_LED; // the number of the LED pin

 

// Variables will change:

int ledState = HIGH; // the current state of the output pin

int buttonState; // the current reading from the input pin

int lastButtonState = LOW; // the previous reading from the input pin

 

// the following variables are long's because the time, measured in miliseconds,

// will quickly become a bigger number than can be stored in an int.

long lastDebounceTime = 0; // the last time the output pin was toggled

long debounceDelay = 50; // the debounce time; increase if the output flickers

 

void setup() {

pinMode(buttonPin, INPUT_PULLUP);

pinMode(ledPin, OUTPUT);

}

 

void loop() {

// read the state of the switch into a local variable:

int reading = digitalRead(buttonPin);

 

// check to see if you just pressed the button

// (i.e. the input went from LOW to HIGH), and you've waited

// long enough since the last press to ignore any noise:

 

// If the switch changed, due to noise or pressing:

if (reading != lastButtonState) {

// reset the debouncing timer

lastDebounceTime = millis();

}

 

if ((millis() - lastDebounceTime) > debounceDelay) {

// whatever the reading is at, it's been there for longer

// than the debounce delay, so take it as the actual current state:

buttonState = reading;

}

 

// set the LED using the state of the button:

digitalWrite(ledPin, buttonState);

 

// save the reading. Next time through the loop,

// it'll be the lastButtonState:

lastButtonState = reading;

}


 

// this constant won't change:

const int buttonPin = PUSH2; // the pin that the pushbutton is attached to

const int ledPin = RED_LED; // the pin that the LED is attached to

 

// Variables will change:

int buttonPushCounter = 0; // counter for the number of button presses

int buttonState = 0; // current state of the button

int lastButtonState = 0; // previous state of the button

 

void setup() {

// initialize the button pin as a input:

pinMode(buttonPin, INPUT_PULLUP);

// initialize the LED as an output:

pinMode(ledPin, OUTPUT);

// initialize serial communication:

Serial.begin(9600);

}

 

 

void loop() {

// read the pushbutton input pin:

buttonState = digitalRead(buttonPin);

 

// compare the buttonState to its previous state

if (buttonState != lastButtonState) {

// if the state has changed, increment the counter

if (buttonState == HIGH) {

// if the current state is HIGH then the button

// wend from off to on:

buttonPushCounter++;

Serial.println("on");

Serial.print("number of button pushes: ");

Serial.println(buttonPushCounter);

}

else {

// if the current state is LOW then the button

// wend from on to off:

Serial.println("off");

}

}

// save the current state as the last state,

//for next time through the loop

lastButtonState = buttonState;

 

 

// turns on the LED every four button pushes by

// checking the modulo of the button push counter.

// the modulo function gives you the remainder of

// the division of two numbers:

if (buttonPushCounter % 4 == 0) {

digitalWrite(ledPin, HIGH);

} else {

digitalWrite(ledPin, LOW);

}

 

}


 

3.Подключить пьезокерамический излучатель между выводами 20 (GND) и 15 (цифровой выход P1.7) микроконтроллера. Написать и отладить программу генерации последовательности звуковых сигналов (не менее трех), сопровождающихся миганием светодиодов. Произвести прошивку программы в микроконтроллер и проверить ее работу.

const int buttonPin = PUSH2; // номер вывода для кнопки

int buttonState = 0; // переменная для чтения статуса кнопки

int numberSound = 0; //номер звука

int previousButtonState=0; // прошлое значение клавиши

void setup()

{

// put your setup code here, to run once:

pinMode(15,OUTPUT); //иницаиализация 15 пина

pinMode(buttonPin, INPUT_PULLUP); //иницаиализация кнопки

pinMode(RED_LED,OUTPUT); //иницаиализация светодиода

}

void loop()

{

buttonState = digitalRead(buttonPin); // чтение статуса кнопки в переменную

 

if (buttonState !=previousButtonState) //если изменено состояние клавиши

{

numberSound++; //увеличение номера звука

}

tone(15,((numberSound%10)+1)*500,10); //вывод звука на 15 порт

digitalWrite(RED_LED,(millis()/(((numberSound%10)+1)*50)%2)); //управление миганием светодиода от функции millis

previousButtonState=buttonState; //присваивание последнего значения кнопки

}

 

4.Написать и отладить программу имитации работы счетчика нажатий кнопки.

· коэффициент счета счетчика должен быть равен номеру рабочего места плюс 2;

 

 

const int buttonPin = PUSH2; // the number of the pushbutton pin

const int ledPin = GREEN_LED; // the number of the LED pin

 

 

int ledState = HIGH; // the current state of the output pin

int buttonState; // the current reading from the input pin

int lastButtonState = LOW; // the previous reading from the input pin

int count=0; //счетчик

 

 

void setup() {

pinMode(buttonPin, INPUT_PULLUP); //инициализация кнопки

pinMode(RED_LED, OUTPUT);//инициализация красного светодиода

pinMode(GREEN_LED, OUTPUT); //инициализация зеленого светодиода

}

 

void loop() {

int reading = digitalRead(buttonPin); //считываем клавишу

if (reading==LOW && lastButtonState==HIGH) //если клавиша нажата и предыдущее состояние клавиши была отпущено

{

if(count==8) //если счетчик переполнен

count=0; //сброс счетчика

else

count++; //увеличение счетчика

}

switch(count%3) // управление младшим тритом

{

case 0: //если младший трит равен 0

{

digitalWrite(GREEN_LED,LOW); //зеленый светодиод не горит

break;

}

case 1: //если младший трит равен 1

{

digitalWrite(GREEN_LED,(millis()/500%2)); //зеленый светодиод мигает

break;

}

case 2: //если младший трит равен 2

{

digitalWrite(GREEN_LED,HIGH); //зеленый светодиод горит

break;

}

}

switch(count/3) // управление старшим тритом

{

case 0: //если старший трит равен 0

{

digitalWrite(RED_LED,LOW); //красный светодиод не горит

break;

}

case 1: //если старший трит равен 1

{

digitalWrite(RED_LED,(millis()/500%2)); //красный светодиод мигает

break;

}

case 2: //если старший трит равен 2

{

digitalWrite(RED_LED,HIGH); //красный светодиод горит

break;

}

}

lastButtonState = reading; //присваивание последнего значения кнопки

}

 

 

Вывод: В ходе данной лабораторной работы изучили основные характеристики и архитектуры микроконтроллера MSP430, интерфейс отладочного модуля MSP430 LaunchPad, выполнили основные приемы программирования микроконтроллера MSP430. Создали простые программы управления цифровыми линиями порта ввода-вывода для отладочного модуля MSP430 LaunchPad с помощью среды программирования Energia.

 

 



<== предыдущая лекция | следующая лекция ==>
История | Научно-методический анализ темы


Карта сайта Карта сайта укр


Уроки php mysql Программирование

Онлайн система счисления Калькулятор онлайн обычный Инженерный калькулятор онлайн Замена русских букв на английские для вебмастеров Замена русских букв на английские

Аппаратное и программное обеспечение Графика и компьютерная сфера Интегрированная геоинформационная система Интернет Компьютер Комплектующие компьютера Лекции Методы и средства измерений неэлектрических величин Обслуживание компьютерных и периферийных устройств Операционные системы Параллельное программирование Проектирование электронных средств Периферийные устройства Полезные ресурсы для программистов Программы для программистов Статьи для программистов Cтруктура и организация данных


 


Не нашли то, что искали? Google вам в помощь!

 
 

© life-prog.ru При использовании материалов прямая ссылка на сайт обязательна.

Генерация страницы за: 0.238 сек.