LoginSignup
0
0

More than 3 years have passed since last update.

AVRマイコンでいろいろやる②-3 シリアル通信3

Posted at

ATmega328Pを使用してWindowsから受け取った値をインクリメントしてWindowsへ返すことを行いました。
これによりマイコンでのデータ受信、送信の両方の確認を行います。

Windows側のプログラムは以下の通りです。
しばらくいじって無くてVisualStudioだけはアップデートしてたら
なぜかSystem.IO.Portsが認識してくれませんでした。
NuGetパッケージ管理で探したら見つかったので
これをインストールしたら無事認識してくれました。

Program.cs
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OnBoardTester
{
    class Program
    {
        static void Main(string[] args)
        {
            //受信Only
            SerialPort serialPort = new SerialPort("COM3", 500000, Parity.None, 8, StopBits.One);
            serialPort.Open();

            byte[] counter = { 0 };
            byte rcv;

            while (true)
            {
                serialPort.Write(counter, 0, 1);
                rcv = (byte)serialPort.ReadByte();

                System.Console.WriteLine(rcv.ToString("x2") + "\n");

                counter[0] = rcv;
            }
        }
    }
}

期待する動作は1通信ごとに値が1増えた値がかえってきて
さらにそれをまたマイコンに入力してと、
1往復ごとに1ずつ増えていくことを想定しています。

マイコン側は以下の通りです。

main.c
#include <avr/io.h>
#include <avr/interrupt.h>

void InitC(){
    DDRC = 0b00111111;
}
int main(void)
{

    /* Replace with your application code */

    //int mode =0;
    InitC();
    PORTC = 1;  //PORTCはデバッグ用
    UCSR0A = UCSR0A |0b00000010; //倍速設定
    UCSR0B = 0b10011000;
    UCSR0C = 0b00000110;
    UBRR0 = 4;
    PORTC = 2;

    sei();//割込み有効

    while(1)
    {

    }
}
ISR(USART_RX_vect){
    unsigned char data;
    data =UDR0;
    PORTC =data;
    while ( !(UCSR0A & (1<<5)) );
    UDR0 = data + 1;
}

受信したら割込みが働き、
即PC側にインクリメントした値を送ります。

実行結果は以下のような感じです。
image.png

次は・・・・何する予定化も忘れましたが、
AD変換でもしますかね。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0