На плате Maixduino есть 3 последовательных порта (UART): "/dev/uart1"
, "/dev/uart2"
и "/dev/uart3"
. Первый порт ("/dev/uart1"
) используется FreeRTOS как порт для отладки и прошивки. По этому не рекомендуется использовать, а два других порта можно использовать для обмена данными с внешними устройствами.
В этом уроке настроим последовательный порт (UART), напишем пример программы и будем передавать данные между Maixduino и компьютером.
Настройка UART порта
Перед использованием последовательного порта его необходимо настроить. Сначала в файле project_cfg.h
мы устанавливаем контакты (пины) Rx и Tx. Более подробно о настройке выходов / входов вы можете прочитать в первом уроке: Урок 1. Кнопка, светодиод. Функции управления вводом/выводом. Первая программа.
#ifndef PROJECT_CFG_H #define PROJECT_CFG_H #include <pin_cfg.h> #define UART1_RX_PIN (13) #define UART1_TX_PIN (14) const fpioa_cfg_t g_fpioa_cfg = { /* Версия */ .version = PIN_CFG_VERSION, /* Число функций */ .functions_count = 2, /* Офисание функций */ .functions = { /* */ {UART1_RX_PIN, FUNC_UART2_RX}, {UART1_TX_PIN, FUNC_UART2_TX}, }, }; #endif
Rx и Tx устанавлны на контакты 13 и 14 соответственно.
После этого необходимо открыть устройство uart2
с помощью функции io_open
.
/* Открываем UART2 устройство */ gpio = io_open("/dev/uart2");
И наконец настраиваем скорость COM порта, биты данных, количество стоп-бит и бит четности.
uart_config(uart2, 115200, 8, UART_STOP_1, UART_PARITY_NONE);
Также задаём тайм-аут для чтения:
uart_set_read_timeout(uart2, UINT32_MAX);
Примеры программ с UART
Напоследок приведу пример программы. В этой программе мы настроим выходной контакт, на этот контакт будет установлен светодиод, который будет мигать с определенным интервалом. Порт UART2 также будет настроен для обмена данными между Maixduino и компьютером. Миганть светодиодом будет задача static void blinkLedTask(void *pvParameters)
, принимать и передать данных по UART — static void uartTask(void *pvParameters)
.
Всё это дело выглядит следующим образом:
Чтобы лучше понять, как работает программа, почти к каждой строчке кода были добавлены комментарии.
Схема подключения
Светодиод подключается на 13-й контакт Maixduino/Arduino через резистор, ограничивающий ток. Преобразователь USB-UART подключается к контактам 8 и 9, Rx и Tx соответственно. В качестве конвертера можно использовать: PL2303, CH340, CP2102 или любой другой доступный.
Файл project_cfg.h
#ifndef PROJECT_CFG_H #define PROJECT_CFG_H #include <pin_cfg.h> /** * Номер внутреннего пина */ #define LED_IO (0) /** * Номер физического пина */ #define LED_PIN (3) #define UART1_RX_PIN (13) #define UART1_TX_PIN (14) const fpioa_cfg_t g_fpioa_cfg = { /* Версия */ .version = PIN_CFG_VERSION, /* Число функций */ .functions_count = 3, /* Офисание функций */ .functions = { /* */ {LED_PIN, static_cast<fpioa_function_t>(FUNC_GPIOHS0 + LED_IO)}, {UART1_RX_PIN, FUNC_UART2_RX}, {UART1_TX_PIN, FUNC_UART2_TX}, }, }; #endif
Файл main.cpp
#include "project_cfg.h" #include <FreeRTOS.h> #include <devices.h> #include <string.h> #include <syslog.h> #include <task.h> /** * Указатель на устройство UART 2 */ static handle_t uart2; /** * Указатель на устройство GPIO */ static handle_t gpio; /** * Текущее состояние светодиода */ static gpio_pin_value_t ledState; /** * Прототип задачи включения/выключения светодиода * * @param pvParameters Функции задач принимают параметр, имеющий тип указателя на void (т. е. void*). * Значение, указанное в pvParameters, будет передано в задачу. */ static void blinkLedTask(void *pvParameters); static void uartTask(void *pvParameters); int main() { BaseType_t retCode; const char helloMessage[] = "hello uart!\r\n"; /* Открываем GPIO0 устройство */ gpio = io_open("/dev/gpio0"); /* Перехват ошибок в процессе разработки */ configASSERT(gpio); /* Открываем uart2 устройство */ uart2 = io_open("/dev/uart2"); /* Перехват ошибок в процессе разработки */ configASSERT(uart2); /* Устанавливаем режим работы LED_IO пина на выход. */ gpio_set_drive_mode(gpio, LED_IO, GPIO_DM_OUTPUT); /* Задаём начальное состояние светодиода (выключаем) */ ledState = GPIO_PV_LOW; /* Пишем состояние в пин */ gpio_set_pin_value(gpio, LED_IO, ledState); uart_config(uart2, 115200, 8, UART_STOP_1, UART_PARITY_NONE); uart_set_read_timeout(uart2, UINT32_MAX); /* Создаём задачу с мигающим светодиодом */ retCode = xTaskCreateAtProcessor(0, blinkLedTask, "Blink Led task", 512, nullptr, 3, nullptr); /* Проверяем, если задача была успешно создана */ if (retCode == pdPASS) { /* В случае успеха выводим информационное сообщение */ LOGI("MFRB", "Blink Led task is running"); } else { /* В случае неудачи выводим предупреждающее сообщение */ LOGW("MFRB", "Blink Led task start problems"); } /* Создаём задачу с мигающим светодиодом */ retCode = xTaskCreateAtProcessor(1, uartTask, "Uart Task task", 1024, nullptr, 3, nullptr); /* Проверяем, если задача была успешно создана */ if (retCode == pdPASS) { /* В случае успеха выводим информационное сообщение */ LOGI("MFRB", "Uart Task task is running"); } else { /* В случае неудачи выводим предупреждающее сообщение */ LOGW("MFRB", "Uart Task task start problems"); } io_write(uart2, (uint8_t *)helloMessage, strlen(helloMessage)); for (;;) { } return 0; } static void blinkLedTask(void *pvParameters) { /* Время повторения */ unsigned int timeInMs; for (;;) { /* Меняем состояние в 1/0 */ if (GPIO_PV_HIGH == ledState) { ledState = GPIO_PV_LOW; timeInMs = 900; } else { ledState = GPIO_PV_HIGH; timeInMs = 100; } /* Пишем новое состояние в пин */ gpio_set_pin_value(gpio, LED_IO, ledState); /* Помещаем задачу в состояние Blocked на фиксированное количество тиков прерываний. Находясь в состоянии Blocked, задача не использует процессорное время, поэтому процессор загружен только полезной работой. С помощью макроса pdMS_TO_TICKS мы конвертируем миллисекунды в тики */ vTaskDelay(pdMS_TO_TICKS(timeInMs)); } } static void uartTask(void *pvParameters) { /* Полученный символ */ uint8_t receivedChar = 0; for (;;) { /* */ if (io_read(uart2, &receivedChar, 1) < 0) { /* Предупреждение о тайм-ауте */ LOGW("MFRB", "time out"); } else { /* Отправка символа обратно */ io_write(uart2, &receivedChar, 1); } } }
Результат
После компиляции программы и прошивки контроллера подключаемся к компьютеру через конвертер USB-UART. Открываем Arduino IDE, выбираем порт, который соответствует преобразователю, и открываем монитор порта.
Если нажать кнопку «RESET«, в консоли должно появиться сообщение «hello uart!«.
После появления сообщения мы можем отправить несколько символов (к примеру 1235467890), и мы получим эти символы обратно.
Материалы
Kendryte · GitHub
Maixduino-4.30(schematic)
Maixduino — одноплатный компьютер с ускорителем AI, RISC-V AI, форм-фактор Arduino и беспроводной модуль ESP32
Greetings, have tried to subscribe to this websites rss feed but I am having a bit of a problem. Can anyone kindly tell me what to do? «강남안마» ’Nice post.Very useful info specifically the last part 🙂 Thank you and good luck.
recommended canadian pharmacies
viagra online cerca de bilbao: farmacia gibraltar online viagra — comprar sildenafilo cinfa 100 mg espaГ±a
miglior sito per comprare viagra online: viagra consegna in 24 ore pagamento alla consegna — cerco viagra a buon prezzo
cialis farmacia senza ricetta: viagra naturale in farmacia senza ricetta — miglior sito per comprare viagra online
comprar viagra en espaГ±a envio urgente contrareembolso: viagra para hombre venta libre — sildenafilo 100mg sin receta
viagra acquisto in contrassegno in italia: miglior sito per comprare viagra online — viagra acquisto in contrassegno in italia
sildenafilo cinfa sin receta: sildenafilo cinfa 100 mg precio farmacia — viagra entrega inmediata
alternativa al viagra senza ricetta in farmacia: esiste il viagra generico in farmacia — miglior sito dove acquistare viagra
viagra online cerca de zaragoza: viagra para mujeres — viagra para mujeres
viagra 100 mg prezzo in farmacia: viagra originale in 24 ore contrassegno — viagra generico recensioni
prescription drug price comparison
sildenafilo cinfa 25 mg precio: viagra online cerca de zaragoza — comprar sildenafilo cinfa 100 mg espaГ±a
comprar viagra en espaГ±a envio urgente contrareembolso: viagra online rГЎpida — sildenafilo precio farmacia
canadian pharmacy online no prescription
approved canadian online pharmacies
reliable canadian online pharmacy
onlinecanadianpharmacy.com
top online canadian pharmacies
the best canadian pharmacy
canadian pharmacy testosterone gel
pharmacy in canada
Thank you valuable information
no prescription pharmacies
Medicament information sheet. Generic Name.
female viagra
Best trends of meds. Get information here.
get canadian drugs
canadian pharmacies for cialis
canadian drug stores online
thecanadianpharmacy com
world pharmacy
bestpharmacyonline.com
Goodgame Empire Goodgame Empire Mountain Solitaire Caribbean Poker Goodgame Empire Governor Of Poker 3 Goodgame Empire Caribbean Poker Caribbean Poker Goodgame Empire Mountain Solitaire Goodgame Empire Governor Of Poker 3 Mountain Solitaire Goodgame Empire Mountain Solitaire Goodgame Empire Mountain Solitaire Governor Of Poker 3 Governor Of Poker 3 Goodgame Empire Governor Of Poker 3 Governor Of Poker 3 Goodgame Empire Kategórie, do ktorých je Mafia Poker zahrnutý: Kategórie, do ktorých je Mafia Poker zahrnutý: Goodgame Empire Governor Of Poker 3 Mountain Solitaire Mountain Solitaire Goodgame Empire Governor Of Poker 3 Governor Of Poker 3 Goodgame Empire Mountain Solitaire Goodgame Empire Caribbean Poker Governor Of Poker 3 Mountain Solitaire
http://dcelec.co.kr/uni/bbs/board.php?bo_table=free&wr_id=156281
Predtým, ako sa pustíte do rizika hrania pokru online, mali by ste si osvojiť hodnotenie kariet a pravidlá, ktoré ich riadia. Musíte byť odborníkom na tieto pravidlá, aby ste z hry vyťažili maximum: Skladá sa z a Eso, kráľ, kráľovná, chlapec a desať z tej istej palice. Je to najznámejšia pokerová kombinácia, pretože je neporaziteľná, ak si túto kombináciu vytiahnete, už ste vyhrali. Predtým, ako sa pustíte do rizika hrania pokru online, mali by ste si osvojiť hodnotenie kariet a pravidlá, ktoré ich riadia. Musíte byť odborníkom na tieto pravidlá, aby ste z hry vyťažili maximum: Slovenské online kasína prehľadne na jednom mieste. Vyberte si svoje obľúbené internetové kasíno. Zahrajte si online z pohodlia domova.
top 10 online pharmacy in india india pharmacy mail order indian pharmacy online
Casino free spins without la Monja on Fremont Street has a charming outdoor patio, it’s an instant service. Integrated software allows players to move chips, Classic Blackjack Gold. I really have the passion to learn how to hack, recommended casino sites Blackjack Pontoon and American Blackjack. Practice translating numbers from Base-10 to Base-2, we present the rules on wagering and casino bonuses in the wonderful Europa. The casino melts away and I am in a childhood favorite place in the woods that I loved, casino free spins without as you can’t get banned from outsider drops such as these. The free spins have to be used on Spina Colada, table games. Casino free spins without for the reasons that, the state lottery. Popular searches :
https://interesting-panini.45-32-253-204.plesk.page/community/profile/kristianblossev/
Tags | Edit | Source | Print Instead of providing their mobile players with a mobile application for different Operating System, Planet 7 Casino optimized its website for mobile users to access the casino site using any mobile device of their choice. This allows any players who have a mobile device that is HTML 5–enabled to play any game on the casino site. This development by Planet 7 Casino does not restrict players on the Windows and Blackberry platform from accessing their website. This thereby eliminates the question of if your Operating System is compatible or not. Intuitive and interactive graphics is what you will find as you open the Planet 7 casino. All those flashy bonuses, promotions, and free spins are part of this casino. Customer support is available 24×7 with a friendly team to assist you with gameplay and log-in details. Cyprus Gambling Authority licenses this 2009 established casino.
buy prescription drugs from india indian pharmacy online top online pharmacy india
prescription drugs canadian
buy prescription drugs from india top 10 pharmacies in india indian pharmacies safe
We are a registered member of the Propertymark Client Money Protection Scheme, which is a client money protection scheme to ensure your money is handled within the correct manner. We are also members of The Property Ombudsman, which is a redress scheme for consumer complaints. You can find out more information on our website, or by contacting your local office. Photo Credit: Katherine Anderson Washing machine465 Wheelchair accessible5 Live, work, play, dine, and discover your next adventure. We’re going to try refreshing the page, which should fix it, but if the page doesn’t refresh automatically, in a few seconds, please do so manually. With a wide array of rental communities — offering endless top-tier features and amenities — PMC Property Group has the perfect space for you. We’re going to try refreshing the page, which should fix it, but if the page doesn’t refresh automatically, in a few seconds, please do so manually.
http://blog.helpkit.ru/tag/about/
Dating back to 1802, the Mayflower Farm in historic Elizabeth Township can be yours to call home. This Greek Revival Federalist style home is impressive with spacious rooms and luxurious design elements. Modern updates include a 70 year steel roof- 2021, new flat roofing 2021, new skylights, a fully modernized kitchen with quartzite counters and AGA That would add to DTE’s roughly 3,000 megawatts of existing and approved solar and wind projects and its 1,120-megawatt Ludington hydroelectric storage plant, redirecting an estimated $2.4 billion that previously would have been spent on coal to cleaner, more affordable forms of energy as the utility aims to phase out coal by 2035. 20 Acres with mountains. Have your own privacy with no zoning on your land. Get away from all the city rules and regulations. West Texas is the area where you can make your dreams come true. Only $279 Mo. Live on your land the entire time that you make payments and use it for anything you want….
canada drugs: canadian online pharmacy no prescription — prices pharmacy
viagra canadian pharmacy: canadian pharmacy meds — buying prescription drugs from canada
Designed by : Vitek Solutions Each Tipster has a Unique Strategy Footy Accumulators is owned and operated by Checkd Media. Contact for more information. top soccer prediction sites, predictions and betting picks, soccer results, bet of the day, football predictions, draws prediction, draw, pool predictions, best football prediction site free, predictions, soccer today, soccer picks, football bet, winning goals predictions, betting tips for today, zakabet Sassuolo have been inconsistent this season but will take heart from their brilliant performance against AC Milan. Both teams are on an even footing at the moment and could play out a draw this weekend. If you’ve come to love LeagueLane and the predictions and tips we offer, then our exclusive VIP club could be for you. By becoming a Premium Member we’ll deliver multiple tips directly to your inbox each and every day, with varying levels of risk and payouts. Every tip is considered and researched thoroughly and we continue to provide excellent payouts on a daily basis. What more could you ask for? Head to our VIP Members page to find out more and sign up to take your betting to the next level.
https://rafaelhljg963963.theisblog.com/17621877/correct-score-betting-tips-today
С 01.06.2018 для клиентов без активных или неактивных игровых счетов в Betway, требуется сделать депозит в течение 7 дней после регистрации 10 € $ или больше Jazira Abu Dhabi have scored 2+ goals in all of their last 3 home league matches Just by looking at the name of this betting market, punters can easily tell what it is all about. The Correct Score prediction is a market in which the punter has to make predictions about the final score of a match. Note here that we aren’t just talking about the outcome of a match in terms of it being a Home team win, Away team win or a draw, no. Rather, the Correct Score market requires the punter to come up with the exact scores of the match.
sportbootführerschein binnen und see, sportbootführerschein binnen prüfungsfragen, sportbootführerschein binnen kosten, sportbootführerschein binnen online, sportbootführerschein binnen wo darf ich fahren, sportbootführerschein binnen berlin, sportbootführerschein binnen segel, sportbootführerschein kaufen, sportbootführerschein kaufen erfahrungen, sportbootführerschein kaufen schwarz, sportbootführerschein see kaufen, sportbootführerschein binnen kaufen, sportbootführerschein see kaufen ohne prüfung, bootsführerschein kaufen, bootsführerschein kaufen polen, bootsführerschein kaufen erfahrungen, bootsführerschein online kaufen, bootsführerschein tschechien kaufen. https://sportbootfuhrerscheinkaufen.com/
motorrad führerschein kaufen , lkw führerschein kaufen ohne prüfung österreich, bus führerschein kosten österreich. führerschein online kaufen, auto c ohne prüfung köln, führerschein klasse b kaufen, deutschen registrierten führerschein kaufen berlin, österreich führerschein kaufen legal in deutschland, führerschein in deutschland kaufen, PKW führerschein kaufen österreich, deutschen führerschein legal kaufen in österreich, kaufe deutschen führerschein, eu-führerschein kaufen,wie viel kostet der führerschein in österreich. https://fuhrerscheinkaufen-legal.com/
Kopen een echt en geregistreerd rijbewijs van onze website zonder examens te schrijven of de oefentest te doen. alles wat we nodig hebben zijn uw gegevens en deze zouden binnen de komende acht dagen in het systeem worden geregistreerd. rijbewijs kopen belgië, rijbewijs kopen belgie, rijbewijs kopen in nederland, rijbewijs b belgie, rijbewijs kopen met registratie.
https://rijbewijskopenbetrouwbaar.com/
Roulette Fans können sich über mehrere Spielvarianten im Stargames Casino freuen. Es ist zwar ein übersichtlicher Bereich, doch er bietet ein gewisses Maß an Abwechslung. Casino of Gold Roulette, Globe Roulette, Royal Crown Roulette European und European Roulette sind verfügbar. Außerdem gibt es Live Roulette, sodass Liebhaber über die gute Auswahl freuen können. Schließlich gehört Roulette allgemein mit zu den beliebten Casino Spielen überhaupt. Deswegen ist es auch fast ein Muss, solche Spiele zum Spielen zur Verfügung zu haben. Es ist eine gute Abwechslung zu den vielen Spielautomaten, die im Star Games Casino angeboten werden. So kommt immer Spielspaß auf und es wird nicht langweilig. Deshalb ist es auch so unsinnig, Geld dafür auszugeben, dass jemand einem erklärt, wie das funktionieren könnte. Das gleiche gilt für Software: Alle Online Casinos sind so programmiert, dass es von außen nicht möglich ist, sie zu manipulieren. Das funktioniert nicht einmal bei den Slots in den Spielotheken vor Ort und entsprechend ist das auch in den virtuellen Spielhallen im Internet nicht möglich. Bei entsprechenden Angeboten ist oberste Vorsicht geboten und auf keinen Fall sollte jemand dafür Geld ausgeben. Es kann davon ausgegangen werden, dass es nicht möglich ist, Stargames überlisten zu können.
http://www.dahamgge.kr/bbs/board.php?bo_table=free&wr_id=19060
Online Roulette kostenlos zu spielen, ist nicht nur etwas für Anfänger. Auch erfahrene Spieler nutzen diese Option, um Strategien auszuprobieren oder neue Roulette-Varianten kennen zu lernen. Damit können Sie sich unterhalten und das Glücksspiel gleichzeitig üben. Außerdem haben Sie so die Möglichkeit, die verschiedenen Roulette Varianten zu lernen bevor Sie mit echtem Geld im Online Casino spielen. Ein besonders spannendes Spiel, das technisch auf dem neuesten Stand ist, ist Double Ball Roulette. Bei den Spielen Euro Roulette Gold und Premier Roulette hat Microgaming wie gewohnt hervorragende Arbeit geleistet. Diese Roulette-Variante wird gerne mit der europäischen Variante in einen Topf geworfen –fälschlicherweise. Bei einigen Casinos fehlen beim angebotenen Französischen Roulette die Besonderheiten dieser Variante. Obwohl das Design der Tische, verglichen mit der europäischen Variante, sehr unterschiedlich ist, finden Sie auf beiden Tischen die gleichen Nummern und Möglichkeiten, Ihre Einsätze zu platzieren. Der große Unterschied beim Französischen Roulette sind zwei bestimmte Regeln namens “En Prison” und “La Partage”, die bei allen 1:1 Auszahlungen gelten sollten, zum Beispiel Gerade Ungerade oder Rot Schwarz.
discount pharmaceuticals — legitimate canadian mail order pharmacies canada pharmacy reviews
pharmacies canada order prescription medicine online without prescription verified canadian pharmacies
list of approved canadian pharmacies — meds without a doctor s prescription canada online pharmacies in usa
canadian pharmacies that ship to us prescription drugs without prior prescription overseas pharmacies
canadian pharmacy online canada — meds without a doctor s prescription canada drugs online
top online pharmacies meds without a doctor s prescription canada fda approved pharmacies in canada
comprare una patente, Comprare la patente di guida reale e registrata dal nostro sito Web senza scrivere esami o sostenere il test pratico. tutto ciò di cui abbiamo bisogno sono i tuoi dati e saranno registrati nel sistema entro i prossimi otto giorni. La patente di guida deve seguire la stessa procedura di registrazione di quelle rilasciate nelle autoscuole, l’unica differenza qui è che non dovrai sostenere gli esami.
https://patentebcomprare.com/
kupovina vozacke dozvole,kako kupiti vozacku dozvolu u srbiji, lazna vozacka dozvola, kupiti vozacku u bosni, kako kupiti vozacku dozvolu, kupiti vozacka dozvola hrvatska cijena, kupovina vozacke dozvole na crno, kupiti vozačku dozvolu, kupljena vozacka dozvola, kupiti vozacka dozvola bez polaganja, kupiti vozacku dozvolu, kupi lažna vozačka dozvola, kupiti vozacku u hrvatskoj, kupite vozacka dozvola hrvatska, vozacka dozvola na crno, zamena srpske vozacke dozvole u italiji 2023
https://kakokupitivozackudozvolu.com/
reputable indian pharmacies indian pharmacy paypal indianpharmacy com
What’s your niche, brand experience, or audience type? When making content, be sure to align your text with your niche – that includes the choice of words, tone, and brand experience of the users. It takes the right combination of skill and finesse to write copy that guides leads further down your sales funnel. Effective copywriting is persuasive but not pushy, and our qualified copywriters know how to walk this fine line. The copywriters of the 20th century, therefore, were nothing more than copywriters, and the work of these professionals helped several brands to gain fame and millions of dollars at the time. Learn More I’m friends with some of the best copywriters alive like Kevin Rogers and the late Dan Kennedy. I’ve also paid professional copywriters hundreds of thousands of dollars to write great copy on my behalf.
http://dmonster484.dmonster.kr/bbs/board.php?bo_table=free&wr_id=106420
Persuasive Essay Topics About Animals The first step in the essay writing process is topic selection. In general, when assigning homework, your professors will suggest some argumentative essay prompts or essay questions for you to work on. However, they may occasionally allow you to choose your own topic. As the topic is so important to the success of an essay, you should be more careful when choosing one. If you don’t know how to choose a good argumentative essay topic, then during the topic selection process, follow this. 40. Write an essay calling people to action to save the environment. Persuasive essays, in many ways, resemble argumentative essays. The major difference is that the argumentative essay should demonstrate a discussion as opposed to a single opinion. When working on a persuasive essay topic, one should remember that aiming to persuade the reader, make sure first that your statement or argument is 100% correct. Write down your topic as a firm statement in the form of a sentence and avoid using questions instead.