개발자/Raspberry Pi

강력한 시리얼 통신 프로그램 UART, Serial to USB 코드

지구빵집 2018. 2. 9. 17:53
반응형

 

 

리눅스 환경, 특히 임베디드 리눅스를 지원하는 라즈베리파이에서 UART 시리얼 통신을 하는 경우가 있는데, 이때 꼭 필요한 작고 강력한 프로그램입니다. 아래 소스코드까지 있어서 잘 활용하면 테스트하는 데 많은 도움이 될 것입니다.  

 

기가막힌 작고 간단한 시리얼 통신 프로그램 UART, Serial to USB 코드 

 

LoRa 무선 통신 모듈을 테스트 하는데 여러 코드들을 참고해서 돌려도 잘 안되던 차에 이것을 발견했다. 154 라인에 불과하지만 정말 대단하게 잘된다. 테스트고 머고 시험 끝났다. 놀자~ㅎㅎ

 

통신 테스트 할 때, 특히 씨리얼 통신처럼 물리적 선으로 연결하여 통신 테스트 할 때는 한단계씩 테스트 하면서 위로 올라가는 방법이 좋다. 무턱대고 연결하고 테스트 하다가 잘 안되는 경우 다시 처음부터 하나씩 하게 되니 말이다. 이때 가능하면 loopback 테스트를 하는 것이다.

 

보통 아두이노나 라즈베리 파이 Serial 포트를 사용할때 자주 사용하는 케이블이 USB to Serial TTL 출력 케이블인 FTDI 케이블을 보자.

 

 

 

이런 게이블을 사용할 때 제대로 데이터가 나오는지 알기 위해 Tx 와 Rx 를 직접 연결한다. 그러면 아래 com 프로그램을 사용하든 다른 통신 프로그램을 사용하든 입력된 문자가 나오면 제대로 동작한다는 뜻이다.

 

반응형

 

아래는 위 케이블의 송 수신 포트를 직접 연결한 것이다.

 

 

통신 프로그램 테스트시 위 사진 처럼 loopback 연결이 되면 문자가 타이핑 되는게 보이고, 연결을 빼면 타이핑을 해도 화면에 문자가 나오지 않는다. 

 

그럼 통신 테스트 프로그램으로 가보자.

 

링크 참조 - 링크 - Tiny serial terminal. http://www.brokestream.com/tinyserial.html

 

중간에 컴파일, 사용방법이 나와있다. 아래와 같은 글의 com.c 링크로 들어가서 다운로드 할 수 있다.

 

1
2
3
4
5
6
7
8
9
There is a teletype tool written by Clifford Wolf based on tinyserial which is much more advanced.
 
Download: com.c
Building: cc -o com com.c
Usage   : ./com /dev/device [speed]
Example : ./com /dev/ttyS0 [115200]
Keys    : Ctrl-- exit, Ctrl-- display control lines status
Darcs   : darcs get http://tinyserial.sf.net/
Scr.shot: screenshot.png (8862 bytes)
cs

 

사용법을 간단히 설명한다. 편의상 라즈베리 USB 포트에 Serial to USB 변환 보드가 연결되어 있다면 아래와 같은 명령으로 USB 장치를 확인한다. $lsusb 명령으로 USB 장치를 볼 수 있다.

 

아래 화면에서는 device 007 이 Serial to USB 변환보드이다. 

 

1
2
3
4
5
6
7
8
9
pi@raspberrypi:~ $ lsusb
Bus 001 Device 005: ID 173d:0004
Bus 001 Device 008: ID 04f3:0235 Elan Microelectronics Corp.
Bus 001 Device 007: ID 10c4:ea60 Cygnal Integrated Products, Inc. CP210x UART Bridge / myAVR mySmartUSB light
Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp. SMSC9512/9514 Fast Ethernet Adapter
Bus 001 Device 002: ID 0424:9514 Standard Microsystems Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
pi@raspberrypi:~ $
 
cs

 

확인이 되었으면 다음과 같은 명령어로 어떤 디바이스로 할당되었는지 이름을 알아야 한다. $dmesg 

긴 실행 메세지가 나온다. 관심 갖지 말자. 제일 마지막 줄을 보면 

[ 779.294957] usb 1-1.2: cp210x converter now attached to ttyUSB0

 

이런 메세지가 나오는데 바로 ttyUSB0 에 할당된것이 보인다. 이것이 포트이름이다. 디바이스 확인 명령어는 다음 확인 명령어로도 볼 수 있다. 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
pi@raspberrypi:~/loracom $  dmesg
[    0.000000] Booting Linux on physical CPU 0x0
[    0.000000] Initializing cgroup subsys cpuset
[    0.000000] Initializing cgroup subsys cpu
[    0.000000] Initializing cgroup subsys cpuacct
[    0.000000] Linux version 4.4.13-v7+ (dc4@dc4-XPS13-9333) (gcc version 4.9.3 (crosstool-NG crosstool-ng-1.22.0-88-g8460611) ) #894 SMP Mon Jun 13 13:13:27 BST 2016
[    0.000000] CPU: ARMv7 Processor [410fd034] revision 4 (ARMv7), cr=10c5383d
[    0.000000] CPU: PIPT / VIPT nonaliasing data cache, VIPT aliasing instruction cache
[    0.000000] Machine model: Raspberry Pi 3 Model B Rev 1.2
[    0.000000] cma: Reserved 8 MiB at 0x36800000
[    0.000000] Memory policy: Data cache writealloc
[    0.000000] On node 0 totalpages: 225280
[    0.000000] free_area_init_node: node 0, pgdat 808c0e00, node_mem_map b6036000
[    0.000000]   Normal zone: 1980 pages used for memmap
[    0.000000]   Normal zone: 0 pages reserved
[    0.000000]   Normal zone: 225280 pages, LIFO batch:31
[    0.000000] [bcm2709_smp_init_cpus] enter (9520->f3003010)
[    0.000000] [bcm2709_smp_init_cpus] ncores=4
[    0.000000] PERCPU: Embedded 13 pages/cpu @b5ff2000 s22592 r8192 d22464 u53248
[    0.000000] pcpu-alloc: s22592 r8192 d22464 u53248 alloc=13*4096
[    0.000000] pcpu-alloc: [00 [01 [02 [03
[    0.000000] Built 1 zonelists in Zone order, mobility grouping on.  Total pages: 223300
[    0.000000] Kernel command line: 8250.nr_uarts=1 dma.dmachans=0x7f35 bcm2708_fb.fbwidth=1280 bcm2708_fb.fbheight=1024 bcm2709.boardrev=0xa02082 bcm2709.serial=0xc77fd079 smsc95xx.macaddr=B8:27:EB:7F:D0:79 bcm2708_fb.fbswap=1 bcm2709.uart_clock=48000000 vc_mem.mem_base=0x3dc00000 vc_mem.mem_size=0x3f000000  dwc_otg.lpm_enable=0 console=ttyS0,115200 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline fsck.repair=yes rootwait
[    0.000000] PID hash table entries: 4096 (order: 216384 bytes)
[    0.000000] Dentry cache hash table entries: 131072 (order: 7524288 bytes)
[    0.000000] Inode-cache hash table entries: 65536 (order: 6262144 bytes)
[    0.000000] Memory: 874120K/901120K available (6344K kernel code, 432K rwdata, 1712K rodata, 476K init, 764K bss, 18808K reserved, 8192K cma-reserved)
[    0.000000] Virtual kernel memory layout:
    vector  : 0xffff0000 - 0xffff1000   (   4 kB)
    fixmap  : 0xffc00000 - 0xfff00000   (3072 kB)
    vmalloc : 0xb7800000 - 0xff800000   (1152 MB)
    lowmem  : 0x80000000 - 0xb7000000   ( 880 MB)
    modules : 0x7f000000 - 0x80000000   (  16 MB)
      .text : 0x80008000 - 0x807e6470   (8058 kB)
      .init : 0x807e7000 - 0x8085e000   ( 476 kB)
      .data : 0x8085e000 - 0x808ca108   ( 433 kB)
       .bss : 0x808cd000 - 0x8098c1ac   ( 765 kB)
[    0.000000] SLUB: HWalign=64, Order=0-3, MinObjects=0, CPUs=4, Nodes=1
[    0.000000] Hierarchical RCU implementation.
[    0.000000]  Build-time adjustment of leaf fanout to 32.
[    0.000000] NR_IRQS:16 nr_irqs:16 16
[    0.000000] Architected cp15 timer(s) running at 19.20MHz (phys).
[    0.000000] clocksource: arch_sys_counter: mask: 0xffffffffffffff max_cycles: 0x46d987e47, max_idle_ns: 440795202767 ns
[    0.000008] sched_clock: 56 bits at 19MHz, resolution 52ns, wraps every 4398046511078ns
[    0.000025] Switching to timer-based delay loop, resolution 52ns
[    0.000281] Console: colour dummy device 80x30
[    0.001333] console [tty1] enabled
[    0.001385] Calibrating delay loop (skipped), value calculated using timer frequency.. 38.40 BogoMIPS (lpj=192000)
[    0.001453] pid_max: default32768 minimum: 301
[    0.001788] Mount-cache hash table entries: 2048 (order: 18192 bytes)
[    0.001830] Mountpoint-cache hash table entries: 2048 (order: 18192 bytes)
[    0.002778] Disabling cpuset control group subsystem
[    0.002835] Initializing cgroup subsys io
[    0.002886] Initializing cgroup subsys memory
[    0.002947] Initializing cgroup subsys devices
[    0.002990] Initializing cgroup subsys freezer
[    0.003033] Initializing cgroup subsys net_cls
[    0.003105] CPU: Testing write buffer coherency: ok
[    0.003190] ftrace: allocating 21209 entries in 63 pages
[    0.053661] CPU0: update cpu_capacity 1024
[    0.053727] CPU0: thread -1, cpu 0, socket 0, mpidr 80000000
[    0.053759] [bcm2709_smp_prepare_cpus] enter
[    0.053920] Setting up static identity map for 0x8240 - 0x8274
[    0.055582] [bcm2709_boot_secondary] cpu:1 started (018
[    0.055933] [bcm2709_secondary_init] enter cpu:1
[    0.055976] CPU1: update cpu_capacity 1024
[    0.055982] CPU1: thread -1, cpu 1, socket 0, mpidr 80000001
[    0.056356] [bcm2709_boot_secondary] cpu:2 started (017
[    0.056614] [bcm2709_secondary_init] enter cpu:2
[    0.056634] CPU2: update cpu_capacity 1024
[    0.056640] CPU2: thread -1, cpu 2, socket 0, mpidr 80000002
[    0.056997] [bcm2709_boot_secondary] cpu:3 started (016
[    0.057179] [bcm2709_secondary_init] enter cpu:3
[    0.057199] CPU3: update cpu_capacity 1024
[    0.057205] CPU3: thread -1, cpu 3, socket 0, mpidr 80000003
[    0.057265] Brought up 4 CPUs
[    0.057364] SMP: Total of 4 processors activated (153.60 BogoMIPS).
[    0.057394] CPU: All CPU(s) started in HYP mode.
[    0.057420] CPU: Virtualization extensions available.
[    0.058050] devtmpfs: initialized
[    0.068153] VFP support v0.3: implementor 41 architecture 3 part 40 variant 3 rev 4
[    0.068509] clocksource: jiffies: mask: 0xffffffff max_cycles: 0xffffffff, max_idle_ns: 19112604462750000 ns
[    0.069251] pinctrl core: initialized pinctrl subsystem
[    0.069807] NET: Registered protocol family 16
[    0.074988] DMA: preallocated 4096 KiB pool for atomic coherent allocations
[    0.082223] bcm2709: Mini UART enabled
[    0.082286] hw-breakpoint: found 5 (+1 reserved) breakpoint and 4 watchpoint registers.
[    0.082333] hw-breakpoint: maximum watchpoint size is 8 bytes.
[    0.082512] Serial: AMBA PL011 UART driver
[    0.082668] uart-pl011 3f201000.uart: could not find pctldev for node /soc/gpio@7e200000/uart0_pins, deferring probe
[    0.082873] bcm2835-mbox 3f00b880.mailbox: mailbox enabled
[    0.145817] bcm2835-dma 3f007000.dma: DMA legacy API manager at f3007000, dmachans=0x1
[    0.146417] SCSI subsystem initialized
[    0.146616] usbcore: registered new interface driver usbfs
[    0.146734] usbcore: registered new interface driver hub
[    0.146854] usbcore: registered new device driver usb
[    0.153230] raspberrypi-firmware soc:firmware: Attached to firmware from 2016-06-20 18:18
[    0.180409] clocksource: Switched to clocksource arch_sys_counter
[    0.225182] FS-Cache: Loaded
[    0.225473] CacheFiles: Loaded
[    0.237744] NET: Registered protocol family 2
[    0.238620] TCP established hash table entries: 8192 (order: 332768 bytes)
[    0.238758] TCP bind hash table entries: 8192 (order: 465536 bytes)
[    0.238968] TCP: Hash tables configured (established 8192 bind 8192)
[    0.239083] UDP hash table entries: 512 (order: 216384 bytes)
[    0.239151] UDP-Lite hash table entries: 512 (order: 216384 bytes)
[    0.239397] NET: Registered protocol family 1
[    0.239734] RPC: Registered named UNIX socket transport module.
[    0.239767] RPC: Registered udp transport module.
[    0.239795] RPC: Registered tcp transport module.
[    0.239823] RPC: Registered tcp NFSv4.1 backchannel transport module.
[    0.240941] hw perfevents: enabled with armv7_cortex_a7 PMU driver, 7 counters available
[    0.242274] futex hash table entries: 1024 (order: 465536 bytes)
[    0.255597] VFS: Disk quotas dquot_6.6.0
[    0.255925] VFS: Dquot-cache hash table entries: 1024 (order 04096 bytes)
[    0.258201] FS-Cache: Netfs 'nfs' registered for caching
[    0.259124] NFS: Registering the id_resolver key type
[    0.259189] Key type id_resolver registered
[    0.259217] Key type id_legacy registered
[    0.261563] Block layer SCSI generic (bsg) driver version 0.4 loaded (major 252)
[    0.261743] io scheduler noop registered
[    0.261783] io scheduler deadline registered (default)
[    0.261858] io scheduler cfq registered
[    0.264426] BCM2708FB: allocated DMA memory f6c00000
[    0.264474] BCM2708FB: allocated DMA channel 0 @ f3007000
[    0.284238] Console: switching to colour frame buffer device 160x64
[    0.296155] Serial: 8250/16550 driver, 1 ports, IRQ sharing disabled
[    0.297243] console [ttyS0] disabled
[    0.297360] 3f215040.uart: ttyS0 at MMIO 0x3f215040 (irq = 59, base_baud = 31250000) is a 16550
[    1.028522] console [ttyS0] enabled
[    1.862513] bcm2835-rng 3f104000.rng: hwrng registered
[    1.867957] vc-cma: Videocore CMA driver
[    1.872021] vc-cma: vc_cma_base      = 0x00000000
[    1.876864] vc-cma: vc_cma_size      = 0x00000000 (0 MiB)
[    1.882434] vc-cma: vc_cma_initial   = 0x00000000 (0 MiB)
[    1.888218] vc-mem: phys_addr:0x00000000 mem_base=0x3dc00000 mem_size:0x3f000000(1008 MiB)
[    1.911695] brd: module loaded
[    1.923534] loop: module loaded
[    1.927704] vchiq: vchiq_init_state: slot_zero = 0xb6c80000, is_master = 0
[    1.936278] Loading iSCSI transport class v2.0-870.
[    1.941980] usbcore: registered new interface driver smsc95xx
[    1.947936] dwc_otg: version 3.00a 10-AUG-2012 (platform bus)
[    2.154136] Core Release: 2.80a
[    2.157382] Setting default values for core params
[    2.162357] Finished setting default values for core params
[    2.368452] Using Buffer DMA mode
[    2.371883] Periodic Transfer Interrupt Enhancement - disabled
[    2.377886] Multiprocessor Interrupt Enhancement - disabled
[    2.383638] OTG VER PARAM: 0, OTG VER FLAG: 0
[    2.388126] Dedicated Tx FIFOs mode
[    2.392019] WARN::dwc_otg_hcd_init:1047: FIQ DMA bounce buffers: virt = 0xb6c14000 dma = 0xf6c14000 len=9024
[    2.402173] FIQ FSM acceleration enabled for :
Non-periodic Split Transactions
Periodic Split Transactions
High-Speed Isochronous Endpoints
Interrupt/Control Split Transaction hack enabled
[    2.433367] dwc_otg: Microframe scheduler enabled
[    2.433423] WARN::hcd_init_fiq:413: FIQ on core 1 at 0x80446a60
[    2.443648] WARN::hcd_init_fiq:414: FIQ ASM at 0x80446dd0 length 36
[    2.454183] WARN::hcd_init_fiq:439: MPHI regs_base at 0xb7b1c000
[    2.464474] dwc_otg 3f980000.usb: DWC OTG Controller
[    2.473688] dwc_otg 3f980000.usb: new USB bus registered, assigned bus number 1
[    2.485310] dwc_otg 3f980000.usb: irq 62, io mem 0x00000000
[    2.495147] Init: Port Power? op_state=1
[    2.503236] Init: Power Port (0)
[    2.510788] usb usb1: New USB device found, idVendor=1d6b, idProduct=0002
[    2.521849] usb usb1: New USB device strings: Mfr=3, Product=2, SerialNumber=1
[    2.533398] usb usb1: Product: DWC OTG Controller
[    2.542378] usb usb1: Manufacturer: Linux 4.4.13-v7+ dwc_otg_hcd
[    2.552672] usb usb1: SerialNumber: 3f980000.usb
[    2.562312] hub 1-0:1.0: USB hub found
[    2.570230] hub 1-0:1.01 port detected
[    2.578859] dwc_otg: FIQ enabled
[    2.578868] dwc_otg: NAK holdoff enabled
[    2.578876] dwc_otg: FIQ split-transaction FSM enabled
[    2.578915] Module dwc_common_port init
[    2.579187] usbcore: registered new interface driver usb-storage
[    2.589635] mousedev: PS/2 mouse device common for all mice
[    2.600080] bcm2835-cpufreq: min=600000 max=1200000
[    2.609367] sdhci: Secure Digital Host Controller Interface driver
[    2.619724] sdhci: Copyright(c) Pierre Ossman
[    2.628550] sdhost: log_buf @ b6c13000 (f6c13000)
[    2.710437] mmc0: sdhost-bcm2835 loaded - DMA enabled (>1)
[    2.722309] mmc-bcm2835 3f300000.mmc: mmc_debug:0 mmc_debug2:0
[    2.732287] mmc-bcm2835 3f300000.mmc: DMA channel allocated
[    2.770504] Indeed it is in host mode hprt0 = 00021501
[    2.780583] sdhci-pltfm: SDHCI platform and OF driver helper
[    2.791923] ledtrig-cpu: registered to indicate activity on CPUs
[    2.802738] hidraw: raw HID events driver (C) Jiri Kosina
[    2.812821] usbcore: registered new interface driver usbhid
[    2.822615] usbhid: USB HID core driver
[    2.831128] Initializing XFRM netlink socket
[    2.839537] NET: Registered protocol family 17
[    2.848070] mmc0: host does not support reading read-only switch, assuming write-enable
[    2.848201] Key type dns_resolver registered
[    2.848736] Registering SWP/SWPB emulation handler
[    2.849593] registered taskstats version 1
[    2.849782] vc-sm: Videocore shared memory driver
[    2.849799] [vc_sm_connected_init]: start
[    2.900780] [vc_sm_connected_init]: end - returning 0
[    2.902170] 3f201000.uart: ttyAMA0 at MMIO 0x3f201000 (irq = 87, base_baud = 0) is a PL011 rev2
[    2.902515] of_cfs_init
[    2.902620] of_cfs_init: OK
[    2.938347] Waiting for root device /dev/mmcblk0p2...
[    2.947768] mmc0: new high speed SDHC card at address e624
[    2.950455] usb 1-1new high-speed USB device number 2 using dwc_otg
[    2.950597] Indeed it is in host mode hprt0 = 00001101
[    2.977852] mmcblk0: mmc0:e624 SL16G 14.8 GiB
[    2.991548]  mmcblk0: p1 p2
[    3.017294] mmc1: queuing unknown CIS tuple 0x80 (2 bytes)
[    3.028447] mmc1: queuing unknown CIS tuple 0x80 (3 bytes)
[    3.039535] mmc1: queuing unknown CIS tuple 0x80 (3 bytes)
[    3.051821] mmc1: queuing unknown CIS tuple 0x80 (7 bytes)
[    3.054931] EXT4-fs (mmcblk0p2): INFO: recovery required on readonly filesystem
[    3.054936] EXT4-fs (mmcblk0p2): write access will be enabled during recovery
[    3.150708] usb 1-1: New USB device found, idVendor=0424, idProduct=9514
[    3.161384] usb 1-1: New USB device strings: Mfr=0, Product=0, SerialNumber=0
[    3.173295] hub 1-1:1.0: USB hub found
[    3.175686] mmc1: new high speed SDIO card at address 0001
[    3.190541] hub 1-1:1.05 ports detected
[    3.363757] EXT4-fs (mmcblk0p2): orphan cleanup on readonly fs
[    3.409242] EXT4-fs (mmcblk0p2): 7 orphan inodes deleted
[    3.418622] EXT4-fs (mmcblk0p2): recovery complete
[    3.462514] EXT4-fs (mmcblk0p2): mounted filesystem with ordered data mode. Opts: (null)
[    3.474691] VFS: Mounted root (ext4 filesystem) readonly on device 179:2.
[    3.480443] usb 1-1.1new high-speed USB device number 3 using dwc_otg
[    3.499743] devtmpfs: mounted
[    3.507425] Freeing unused kernel memory: 476K (807e7000 - 8085e000)
[    3.590730] usb 1-1.1: New USB device found, idVendor=0424, idProduct=ec00
[    3.601774] usb 1-1.1: New USB device strings: Mfr=0, Product=0, SerialNumber=0
[    3.616081] smsc95xx v1.0.4
[    3.683778] smsc95xx 1-1.1:1.0 eth0: register 'smsc95xx' at usb-3f980000.usb-1.1, smsc95xx USB 2.0 Ethernet, b8:27:eb:7f:d0:79
[    3.745696] random: systemd urandom read with 76 bits of entropy available
[    3.763475] systemd[1]: systemd 215 running in system mode. (+PAM +AUDIT +SELINUX +IMA +SYSVINIT +LIBCRYPTSETUP +GCRYPT +ACL +XZ -SECCOMP -APPARMOR)
[    3.781875] systemd[1]: Detected architecture 'arm'.
[    3.910985] NET: Registered protocol family 10
[    3.921292] systemd[1]: Inserted module 'ipv6'
[    3.930491] usb 1-1.2new low-speed USB device number 4 using dwc_otg
[    3.946395] systemd[1]: Set hostname to <raspberrypi>.
[    4.045131] usb 1-1.2: New USB device found, idVendor=04f3, idProduct=0235
[    4.056869] usb 1-1.2: New USB device strings: Mfr=0, Product=2, SerialNumber=0
[    4.069628] usb 1-1.2: Product: OM
[    4.086787] input: OM as /devices/platform/soc/3f980000.usb/usb1/1-1/1-1.2/1-1.2:1.0/0003:04F3:0235.0001/input/input0
[    4.102673] hid-generic 0003:04F3:0235.0001: input,hidraw0: USB HID v1.11 Mouse [OM] on usb-3f980000.usb-1.2/input0
[    4.210474] usb 1-1.4new low-speed USB device number 5 using dwc_otg
[    4.365385] systemd[1]: Starting Forward Password Requests to Wall Directory Watch.
[    4.378310] systemd[1]: Started Forward Password Requests to Wall Directory Watch.
[    4.390788] systemd[1]: Expecting device dev-ttyS0.device...
[    4.406848] systemd[1]: Starting Remote File Systems (Pre).
[    4.418798] usb 1-1.4: New USB device found, idVendor=173d, idProduct=0004
[    4.418808] usb 1-1.4: New USB device strings: Mfr=0, Product=0, SerialNumber=0
[    4.446583] systemd[1]: Reached target Remote File Systems (Pre).
[    4.457750] systemd[1]: Starting Arbitrary Executable File Formats File System Automount Point.
[    4.477565] systemd[1]: Set up automount Arbitrary Executable File Formats File System Automount Point.
[    4.492074] systemd[1]: Starting Encrypted Volumes.
[    4.507674] systemd[1]: Reached target Encrypted Volumes.
[    4.518193] systemd[1]: Starting Swap.
[    4.532559] systemd[1]: Reached target Swap.
[    4.541823] systemd[1]: Expecting device dev-mmcblk0p1.device...
[    4.555880] input: HID 173d:0004 as /devices/platform/soc/3f980000.usb/usb1/1-1/1-1.4/1-1.4:1.0/0003:173D:0004.0002/input/input1
[    4.575466] systemd[1]: Starting Root Slice.
[    4.590987] systemd[1]: Created slice Root Slice.
[    4.600991] systemd[1]: Starting User and Session Slice.
[    4.611137] hid-generic 0003:173D:0004.0002: input,hidraw1: USB HID v1.10 Keyboard [HID 173d:0004] on usb-3f980000.usb-1.4/input0
[    4.635134] systemd[1]: Created slice User and Session Slice.
[    4.646366] systemd[1]: Starting Delayed Shutdown Socket.
[    4.663449] systemd[1]: Listening on Delayed Shutdown Socket.
[    4.674691] systemd[1]: Starting /dev/initctl Compatibility Named Pipe.
[    4.693162] systemd[1]: Listening on /dev/initctl Compatibility Named Pipe.
[    4.705724] systemd[1]: Starting Journal Socket (/dev/log).
[    4.723158] systemd[1]: Listening on Journal Socket (/dev/log).
[    4.734671] systemd[1]: Starting udev Control Socket.
[    4.751417] systemd[1]: Listening on udev Control Socket.
[    4.762334] systemd[1]: Starting udev Kernel Socket.
[    4.778829] systemd[1]: Listening on udev Kernel Socket.
[    4.789507] systemd[1]: Starting Journal Socket.
[    4.805237] systemd[1]: Listening on Journal Socket.
[    4.815522] systemd[1]: Starting System Slice.
[    4.831153] systemd[1]: Created slice System Slice.
[    4.841244] systemd[1]: Starting File System Check on Root Device...
[    4.853348] input: HID 173d:0004 as /devices/platform/soc/3f980000.usb/usb1/1-1/1-1.4/1-1.4:1.1/0003:173D:0004.0003/input/input2
[    4.911069] hid-generic 0003:173D:0004.0003: input,hiddev0,hidraw2: USB HID v1.10 Device [HID 173d:0004] on usb-3f980000.usb-1.4/input1
[    4.911083] systemd[1]: Starting system-systemd\x2dfsck.slice.
[    4.946423] systemd[1]: Created slice system-systemd\x2dfsck.slice.
[    4.958489] systemd[1]: Starting system-autologin.slice.
[    4.975435] systemd[1]: Created slice system-autologin.slice.
[    4.986497] systemd[1]: Starting system-serial\x2dgetty.slice.
[    5.003694] systemd[1]: Created slice system-serial\x2dgetty.slice.
[    5.015357] systemd[1]: Starting Increase datagram queue length...
[    5.062867] systemd[1]: Starting Restore / save the current clock...
[    5.085220] systemd[1]: Mounted Huge Pages File System.
[    5.096400] systemd[1]: Starting Create list of required static device nodes for the current kernel...
[    5.127390] systemd[1]: Starting Load Kernel Modules...
[    5.161248] systemd[1]: Started Set Up Additional Binary Formats.
[    5.178523] systemd[1]: Mounting Debug File System...
[    5.214462] fuse init (API version 7.23)
[    5.233638] i2c /dev entries driver
[    5.242766] systemd[1]: Starting udev Coldplug all Devices...
[    5.263600] systemd[1]: Mounting POSIX Message Queue File System...
[    5.284395] systemd[1]: Starting Slices.
[    5.300508] systemd[1]: Reached target Slices.
[    5.318018] systemd[1]: Mounted POSIX Message Queue File System.
[    5.334806] systemd[1]: Mounted Debug File System.
[    5.351015] systemd[1]: Started File System Check on Root Device.
[    5.379650] systemd[1]: Started Increase datagram queue length.
[    5.397067] systemd[1]: Started Restore / save the current clock.
[    5.414602] systemd[1]: Started Create list of required static device nodes for the current kernel.
[    5.435431] systemd[1]: Started Load Kernel Modules.
[    5.477196] systemd[1]: Time has been changed
[    5.527332] systemd[1]: Started udev Coldplug all Devices.
[    5.648805] systemd[1]: Mounting Configuration File System...
[    5.690853] systemd[1]: Starting Apply Kernel Variables...
[    5.710138] systemd[1]: Mounting FUSE Control File System...
[    5.730493] systemd[1]: Starting Create Static Device Nodes in /dev...
[    5.740018] systemd[1]: Starting Syslog Socket.
[    5.746586] systemd[1]: Listening on Syslog Socket.
[    5.746744] systemd[1]: Starting Journal Service...
[    5.762053] systemd[1]: Started Journal Service.
[    5.942114] systemd-udevd[138]: starting version 215
[    6.260329] bcm2835-wdt 3f100000.watchdog: Broadcom BCM2835 watchdog timer
[    6.336389] gpiomem-bcm2835 3f200000.gpiomem: Initialised: Registers at 0x3f200000
[    6.559731] usbcore: registered new interface driver brcmfmac
[    6.584507] EXT4-fs (mmcblk0p2): re-mounted. Opts: (null)
[    6.689687] brcmfmac: brcmf_c_preinit_dcmds: Firmware version = wl0: May 27 2016 00:13:38 version 7.45.41.26 (r640327) FWID 01-df77e4a7
[    6.712353] random: nonblocking pool is initialized
[    6.715088] brcmfmac: brcmf_cfg80211_reg_notifier: not a ISO3166 code
[    6.991757] brcmfmac: brcmf_cfg80211_reg_notifier: not a ISO3166 code
[    6.991782] cfg80211: World regulatory domain updated:
[    6.991791] cfg80211:  DFS Master region: unset
[    6.991800] cfg80211:   (start_freq - end_freq @ bandwidth), (max_antenna_gain, max_eirp), (dfs_cac_time)
[    6.991814] cfg80211:   (2402000 KHz - 2472000 KHz @ 40000 KHz), (N/A, 2000 mBm), (N/A)
[    6.991828] cfg80211:   (2457000 KHz - 2482000 KHz @ 40000 KHz), (N/A, 2000 mBm), (N/A)
[    6.991840] cfg80211:   (2474000 KHz - 2494000 KHz @ 20000 KHz), (N/A, 2000 mBm), (N/A)
[    6.991854] cfg80211:   (5170000 KHz - 5250000 KHz @ 80000 KHz, 160000 KHz AUTO), (N/A, 2000 mBm), (N/A)
[    6.991868] cfg80211:   (5250000 KHz - 5330000 KHz @ 80000 KHz, 160000 KHz AUTO), (N/A, 2000 mBm), (0 s)
[    6.991881] cfg80211:   (5490000 KHz - 5730000 KHz @ 160000 KHz), (N/A, 2000 mBm), (0 s)
[    6.991893] cfg80211:   (5735000 KHz - 5835000 KHz @ 80000 KHz), (N/A, 2000 mBm), (N/A)
[    6.991905] cfg80211:   (57240000 KHz - 63720000 KHz @ 2160000 KHz), (N/A, 0 mBm), (N/A)
[    7.389302] systemd-journald[136]: Received request to flush runtime journal from PID 1
[    7.982817] brcmfmac: brcmf_add_if: ERROR: netdev:wlan0 already exists
[    7.982837] brcmfmac: brcmf_add_if: ignore IF event
[    7.987656] IPv6: ADDRCONF(NETDEV_UP): wlan0: link is not ready
[    7.987704] brcmfmac: power management disabled
[    8.655179] uart-pl011 3f201000.uart: no DMA platform data
[    8.904712] Adding 102396k swap on /var/swap.  Priority:-1 extents:1 across:102396k SSFS
[    9.583195] smsc95xx 1-1.1:1.0 eth0: hardware isn't capable of remote wakeup
[    9.583442] IPv6: ADDRCONF(NETDEV_UP): eth0: link is not ready
[   10.593462] IPv6: ADDRCONF(NETDEV_UP): wlan0: link is not ready
[   10.593514] brcmfmac: power management disabled
[   11.188352] IPv6: ADDRCONF(NETDEV_CHANGE): eth0: link becomes ready
[   11.189399] smsc95xx 1-1.1:1.0 eth0: link up, 100Mbps, full-duplex, lpa 0x45E1
[   13.218881] Bluetooth: Core ver 2.21
[   13.219028] NET: Registered protocol family 31
[   13.219051] Bluetooth: HCI device and connection manager initialized
[   13.220735] Bluetooth: HCI socket layer initialized
[   13.220772] Bluetooth: L2CAP socket layer initialized
[   13.220846] Bluetooth: SCO socket layer initialized
[   13.229501] Bluetooth: HCI UART driver ver 2.3
[   13.229527] Bluetooth: HCI UART protocol H4 registered
[   13.229537] Bluetooth: HCI UART protocol Three-wire (H5) registered
[   13.229766] Bluetooth: HCI UART protocol BCM registered
[   13.529694] Bluetooth: BNEP (Ethernet Emulation) ver 1.3
[   13.529717] Bluetooth: BNEP filters: protocol multicast
[   13.529746] Bluetooth: BNEP socket layer initialized
[   13.774910] brcmfmac: brcmf_add_if: ERROR: netdev:wlan0 already exists
[   13.774930] brcmfmac: brcmf_add_if: ignore IF event
[   13.855200] IPv6: ADDRCONF(NETDEV_CHANGE): wlan0: link becomes ready
[  770.054089] usb 1-1.2: USB disconnect, device number 4
[  772.242099] usb 1-1.3: new low-speed USB device number 6 using dwc_otg
[  772.345918] usb 1-1.3: New USB device found, idVendor=04f3, idProduct=0235
[  772.345938] usb 1-1.3: New USB device strings: Mfr=0, Product=2, SerialNumber=0
[  772.345951] usb 1-1.3: Product: OM
[  772.356745] input: OM as /devices/platform/soc/3f980000.usb/usb1/1-1/1-1.3/1-1.3:1.0/0003:04F3:0235.0004/input/input3
[  772.357862] hid-generic 0003:04F3:0235.0004: input,hidraw0: USB HID v1.11 Mouse [OM] on usb-3f980000.usb-1.3/input0
[  778.132110] usb 1-1.2: new full-speed USB device number 7 using dwc_otg
[  778.238203] usb 1-1.2: New USB device found, idVendor=10c4, idProduct=ea60
[  778.238223] usb 1-1.2: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[  778.238236] usb 1-1.2: Product: CP2104 USB to UART Bridge Controller
[  778.238249] usb 1-1.2: Manufacturer: Silicon Labs
[  778.238261] usb 1-1.2: SerialNumber: 013963DC
[  778.240701] usb 1-1.3: USB disconnect, device number 6
[  778.472101] usb 1-1.3: new low-speed USB device number 8 using dwc_otg
[  778.575874] usb 1-1.3: New USB device found, idVendor=04f3, idProduct=0235
[  778.575893] usb 1-1.3: New USB device strings: Mfr=0, Product=2, SerialNumber=0
[  778.575906] usb 1-1.3: Product: OM
[  778.586180] input: OM as /devices/platform/soc/3f980000.usb/usb1/1-1/1-1.3/1-1.3:1.0/0003:04F3:0235.0005/input/input4
[  778.586921] hid-generic 0003:04F3:0235.0005: input,hidraw0: USB HID v1.11 Mouse [OM] on usb-3f980000.usb-1.3/input0
[  779.290530] usbcore: registered new interface driver usbserial
[  779.290631] usbcore: registered new interface driver usbserial_generic
[  779.290753] usbserial: USB Serial support registered for generic
[  779.294223] usbcore: registered new interface driver cp210x
[  779.294329] usbserial: USB Serial support registered for cp210x
[  779.294498] cp210x 1-1.2:1.0: cp210x converter detected
[  779.294957] usb 1-1.2: cp210x converter now attached to ttyUSB0
pi@raspberrypi:~/loracom $
 
cs

 

바로 아래 명령어다. 네번 째 줄 끝에서 두번 째에 ttyUSB0 가 있다. 소스코드를 다운 받아 실행은 아래 명령어로 한다. $sudo ./com /dev/ttyUSB0 [9600] 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
pi@raspberrypi:~/loracom $ ls /dev
autofs           input             network_latency     ram8       tty12  tty30  tty49  ttyAMA0    vcsa1
block            kmsg              network_throughput  ram9       tty13  tty31  tty5   ttyprintk  vcsa2
btrfs-control    log               null                random     tty14  tty32  tty50  ttyS0      vcsa3
bus              loop0             ppp                 raw        tty15  tty33  tty51  ttyUSB0    vcsa4
cachefiles       loop1             ptmx                rfkill     tty16  tty34  tty52  uhid       vcsa5
char             loop2             pts                 serial     tty17  tty35  tty53  uinput     vcsa6
console          loop3             ram0                serial0    tty18  tty36  tty54  urandom    vcsm
cpu_dma_latency  loop4             ram1                serial1    tty19  tty37  tty55  usb        vhci
cuse             loop5             ram10               shm        tty2   tty38  tty56  vc-cma     watchdog
disk             loop6             ram11               snd        tty20  tty39  tty57  vchiq      watchdog0
fb0              loop7             ram12               spidev0.0  tty21  tty4   tty58  vcio       xconsole
fd               loop-control      ram13               spidev0.1  tty22  tty40  tty59  vc-mem     zero
full             mapper            ram14               stderr     tty23  tty41  tty6   vcs
fuse             mem               ram15               stdin      tty24  tty42  tty60  vcs1
gpiomem          memory_bandwidth  ram2                stdout     tty25  tty43  tty61  vcs2
hidraw0          mmcblk0           ram3                tty        tty26  tty44  tty62  vcs3
hidraw1          mmcblk0p1         ram4                tty0       tty27  tty45  tty63  vcs4
hidraw2          mmcblk0p2         ram5                tty1       tty28  tty46  tty7   vcs5
hwrng            mqueue            ram6                tty10      tty29  tty47  tty8   vcs6
initctl          net               ram7                tty11      tty3   tty48  tty9   vcsa
pi@raspberrypi:~/loracom $
 
cs

 

실행하여 테스트 하는 화면이다. 데이터가 잘 나온다. 보니까 입력하는 즉시 한 바이트씩 보낸다.

 

1
2
3
4
5
6
7
 
pi@raspberrypi:~/loracom $ sudo ./com /dev/ttyUSB0 [9600]
C-a exit, C-x modem lines status
[STATUS]: RTS DTR
to-node
 
 
cs

 

 

아래에 소스코드를 나타내었다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
#include <termios.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/signal.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <errno.h>
 
int transfer_byte(int from, int to, int is_control);
 
typedef struct {char *name; int flag; } speed_spec;
 
 
void print_status(int fd) {
    int status;
    unsigned int arg;
    status = ioctl(fd, TIOCMGET, &arg);
    fprintf(stderr, "[STATUS]: ");
    if(arg & TIOCM_RTS) fprintf(stderr, "RTS ");
    if(arg & TIOCM_CTS) fprintf(stderr, "CTS ");
    if(arg & TIOCM_DSR) fprintf(stderr, "DSR ");
    if(arg & TIOCM_CAR) fprintf(stderr, "DCD ");
    if(arg & TIOCM_DTR) fprintf(stderr, "DTR ");
    if(arg & TIOCM_RNG) fprintf(stderr, "RI ");
    fprintf(stderr, "\r\n");
}
 
int main(int argc, char *argv[])
{
    int comfd;
    struct termios oldtio, newtio;       //place for old and new port settings for serial port
    struct termios oldkey, newkey;       //place tor old and new port settings for keyboard teletype
    char *devicename = argv[1];
    int need_exit = 0;
    speed_spec speeds[] =
    {
        {"1200", B1200},
        {"2400", B2400},
        {"4800", B4800},
        {"9600", B9600},
        {"19200", B19200},
        {"38400", B38400},
        {"57600", B57600},
        {"115200", B115200},
        {NULL0}
    };
    int speed = B9600;
 
    if(argc < 2) {
        fprintf(stderr, "example: %s /dev/ttyS0 [115200]\n", argv[0]);
        exit(1);
    }
 
    comfd = open(devicename, O_RDWR | O_NOCTTY | O_NONBLOCK);
    if (comfd < 0)
    {
        perror(devicename);
        exit(-1);
    }
 
    if(argc > 2) {    
        speed_spec *s;
        for(s = speeds; s->name; s++) {
            if(strcmp(s->name, argv[2]) == 0) {
                speed = s->flag;
                fprintf(stderr, "setting speed %s\n", s->name);
                break;
            }
        }
    }
 
    fprintf(stderr, "C-a exit, C-x modem lines status\n");
 
    tcgetattr(STDIN_FILENO,&oldkey);
    newkey.c_cflag = B9600 | CRTSCTS | CS8 | CLOCAL | CREAD;
    newkey.c_iflag = IGNPAR;
    newkey.c_oflag = 0;
    newkey.c_lflag = 0;
    newkey.c_cc[VMIN]=1;
    newkey.c_cc[VTIME]=0;
    tcflush(STDIN_FILENO, TCIFLUSH);
    tcsetattr(STDIN_FILENO,TCSANOW,&newkey);
 
 
    tcgetattr(comfd,&oldtio); // save current port settings 
    newtio.c_cflag = speed | CS8 | CLOCAL | CREAD;
    newtio.c_iflag = IGNPAR;
    newtio.c_oflag = 0;
    newtio.c_lflag = 0;
    newtio.c_cc[VMIN]=1;
    newtio.c_cc[VTIME]=0;
    tcflush(comfd, TCIFLUSH);
    tcsetattr(comfd,TCSANOW,&newtio);
 
    print_status(comfd);
 
    while(!need_exit) {
        fd_set fds;
        int ret;
        
        FD_ZERO(&fds);
        FD_SET(STDIN_FILENO, &fds);
        FD_SET(comfd, &fds);
 
 
        ret = select(comfd+1&fds, NULLNULLNULL);
        if(ret == -1) {
            perror("select");
        } else if (ret > 0) {
            if(FD_ISSET(STDIN_FILENO, &fds)) {
                need_exit = transfer_byte(STDIN_FILENO, comfd, 1);
            }
            if(FD_ISSET(comfd, &fds)) {
                need_exit = transfer_byte(comfd, STDIN_FILENO, 0);
            }
        }
    }
 
    tcsetattr(comfd,TCSANOW,&oldtio);
    tcsetattr(STDIN_FILENO,TCSANOW,&oldkey);
    close(comfd);
 
    return 0;
}
 
 
int transfer_byte(int from, int to, int is_control) {
    char c;
    int ret;
    do {
        ret = read(from, &c, 1);
    } while (ret < 0 && errno == EINTR);
    if(ret == 1) {
        if(is_control) {
            if(c == '\x01') { // C-a
                return -1;
            } else if(c == '\x18') { // C-x
                print_status(to);
                return 0;
            }
        }
        while(write(to, &c, 1== -1) {
            if(errno!=EAGAIN && errno!=EINTR) { perror("write failed"); break; }
        }
    } else {
        fprintf(stderr, "\nnothing to read. probably port disconnected.\n");
        return -2;
    }
    return 0;
}
 
cs

 

 

컴파일을 하고 실행시에 Baudrate 전송속도를 인자로 넣어주면 된다. 

 

1
2
3
$ gcc -o com com.c (컴파일)
 
$ ./com /dev/ttyUSB0 115200 (실행)
cs

 

전송 속도가 보통 9600 이라면 115200 을 9600 으로 바꿔주고 실행하면 된다.  

 

한가지 첨부하자면 통신 실행시 자신이 입력한 문자가 안나오는 현상을 이렇게 아래처럼 해결했다고 합니다. 코드를 첨부 합니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
 
int transfer_byte(int from, int to, int is_control)
{
    char c;
    int ret;
    do
    {
        ret = read(from, &c, 1);
    } while (ret < 0 && errno == EINTR);
    if (ret == 1)
    {
        if (is_control)
        {
            if (c == '\x01')
            { // C-a
                return -1;
            }
            else if (c == '\x18')
            { // C-x
                print_status(to);
                return 0;
            }
        }
        while (write(to, &c, 1== -1)
        {
            if (errno != EAGAIN && errno != EINTR)
            {
                perror("write failed");
                break;
            }
        }
 
        /*
         * send also to stdout.
         */
        if(to == STDIN_FILENO)
        {
            while (write(STDOUT_FILENO, &c, 1== -1)
            {
                    if (errno != EAGAIN && errno != EINTR)
                    {
                    perror("write failed");
                    break;
                    }
            }
        }
    }
    else
    {
        fprintf(stderr, "\nnothing to read. probably port disconnected.\n");
        return -2;
    }
    return 0;
}
 
 
cs

 

 

참고한 곳 : http://yowon009.tistory.com/771 - 씨리얼 통신 관련된 많은 포스트가 있네요. 20180209 오늘 다시 들어가 보니 이전하신듯 한데 확실한 지는 잘 모릅니다.  http://miruel.egloos.com/v/2689710

 

 

 

 

테스트 사진 몆 장 올립니다.

 

 

 

 

 

 

 

 

 

반응형