Comunicação serial I
Tutorial em vídeo 27 - Comunicação serial enviando dados:
https://singtown.com/learn/50235/
Tutorial em vídeo 28 - Comunicação serial recebendo dados:
https://singtown.com/learn/50240/
Introdução
Por que usar a porta serial? Porque às vezes você precisa enviar informações para outro MCU; a porta serial é simples e universal, basicamente todo MCU possui uma porta serial.
A porta serial TTL precisa de no mínimo três fios: TXD, RXD, GND. TXD é a extremidade de transmissão, RXD é a extremidade de recepção, e GND é o fio terra. Ao fazer a ligação, você precisa conectar o RXD da OpenMV ao TXD de outro MCU, e ligar o TXD ao RXD. Como mostrado na imagem:

import time
from machine import UART
#from pyb import UART
# O UART(3) da OpenMV4 H7 Plus, OpenMV4 H7, OpenMV3 M7, OpenMV2 M4 é P4-TX P5-RX
uart = UART(3, 19200) # Na OpenMV RT, comente esta linha e use a linha UART(1) abaixo
#uart = UART(1, 19200) # Na OpenMV RT, use esta linha UART(1) e comente a linha UART(3) acima
# A OpenMV RT possui apenas a porta serial UART(1), correspondente a P4-TX P5-RX; o UART(1) da OpenMV4 H7 Plus, OpenMV4 H7, OpenMV3 M7 é P0-RX P1-TX
while(True):
uart.write("Hello World!\r")
time.sleep_ms(1000)
Primeiro instancie uma porta serial com taxa de transmissão de 19200 e, em seguida, chame o método write.
Nota: A OpenMV RT possui apenas a porta serial UART(1), correspondente a P4-TX P5-RX.
A porta serial UART(1) da OpenMV4 H7 Plus, OpenMV4 H7, OpenMV3 M7 é P0-RX P1-TX.
A porta serial UART(3) da OpenMV4 H7 Plus, OpenMV4 H7, OpenMV3 M7, OpenMV2 M4 é P4-TX P5-RX
Transmitindo dados complexos
Na seção anterior falamos sobre strings json.
# Blob Detection and uart transport
import csi, image, time
csi0 = csi.CSI()
#from pyb import UART
from machine import UART
import json
# For color tracking to work really well you should ideally be in a very, very,
# very, controlled enviroment where the lighting is constant...
yellow_threshold = (65, 100, -10, 6, 24, 51)
# You may need to tweak the above settings for tracking green things...
# Select an area in the Framebuffer to copy the color settings.
csi0.reset() # Initialize the camera sensor.
csi0.pixformat(csi.RGB565) # use RGB565.
csi0.framesize(csi.QQVGA) # use QQVGA for speed.
csi0.snapshot(frames=10) # Let new settings take affect.
csi0.auto_whitebal(False) # turn this off.
clock = time.clock() # Tracks FPS.
# O UART(3) da OpenMV4 H7 Plus, OpenMV4 H7, OpenMV3 M7, OpenMV2 M4 é P4-TX P5-RX
uart = UART(3, 115200) # Na OpenMV RT, comente esta linha e use a linha UART(1) abaixo
#uart = UART(1, 115200) # Na OpenMV RT, use esta linha UART(1) e comente a linha UART(3) acima
# A OpenMV RT possui apenas a porta serial UART(1), correspondente a P4-TX P5-RX; o UART(1) da OpenMV4 H7 Plus, OpenMV4 H7, OpenMV3 M7 é P0-RX P1-TX
while(True):
img = csi0.snapshot() # Take a picture and return the image.
blobs = img.find_blobs([yellow_threshold])
if blobs:
print('sum :', len(blobs))
output_str = json.dumps(blobs)
for b in blobs:
# Draw a rect around the blob.
img.draw_rectangle(b.rect) # rect
img.draw_cross((b.cx, b.cy)) # cx, cy
print('you send:',output_str)
uart.write(output_str+'\n')
else:
print('not found!')
A saída resultante é:
sum : 1
you send: [{x:17, y:23, w:37, h:12, pixels:178, cx:40, cy:29, rotation:3.060313, code:1, count:1}]
sum : 2
you send: [{x:34, y:24, w:19, h:13, pixels:149, cx:45, cy:30, rotation:3.120370, code:1, count:1}, {x:23, y:30, w:8, h:2, pixels:17, cx:27, cy:30, rotation:0.046378, code:1, count:1}]
Isso enviará todos os blobs.
Simplificando os dados
Mas às vezes você não quer transmitir muitos dados. Por exemplo, quero transmitir apenas as coordenadas x e y do centro do maior bloco de cor.\ Construa os dados que deseja transmitir.
Escreva um loop for e depois escreva uma função find_max().
# Blob Detection and uart transport
import csi, image, time
csi0 = csi.CSI()
#from pyb import UART
from machine import UART
import json
# For color tracking to work really well you should ideally be in a very, very,
# very, controlled enviroment where the lighting is constant...
yellow_threshold = (65, 100, -10, 6, 24, 51)
# You may need to tweak the above settings for tracking green things...
# Select an area in the Framebuffer to copy the color settings.
csi0.reset() # Initialize the camera sensor.
csi0.pixformat(csi.RGB565) # use RGB565.
csi0.framesize(csi.QQVGA) # use QQVGA for speed.
csi0.snapshot(frames=10) # Let new settings take affect.
csi0.auto_whitebal(False) # turn this off.
clock = time.clock() # Tracks FPS.
# O UART(3) da OpenMV4 H7 Plus, OpenMV4 H7, OpenMV3 M7, OpenMV2 M4 é P4-TX P5-RX
uart = UART(3, 115200) # Na OpenMV RT, comente esta linha e use a linha UART(1) abaixo
#uart = UART(1, 115200) # Na OpenMV RT, use esta linha UART(1) e comente a linha UART(3) acima
# A OpenMV RT possui apenas a porta serial UART(1), correspondente a P4-TX P5-RX; o UART(1) da OpenMV4 H7 Plus, OpenMV4 H7, OpenMV3 M7 é P0-RX P1-TX
def find_max(blobs):
max_size=0
for blob in blobs:
if blob.pixels > max_size:
max_blob=blob
max_size = blob.pixels
return max_blob
while(True):
img = csi0.snapshot() # Take a picture and return the image.
blobs = img.find_blobs([yellow_threshold])
if blobs:
max_blob=find_max(blobs)
print('sum :', len(blobs))
img.draw_rectangle(max_blob.rect)
img.draw_cross((max_blob.cx, max_blob.cy))
output_str="[%d,%d]" % (max_blob.cx,max_blob.cy) # forma 1
#output_str=json.dumps([max_blob.cx,max_blob.cy]) # forma 2
print('you send:',output_str)
uart.write(output_str+'\r\n')
else:
print('not found!')
Resultado:
sum : 6
you send: [63,45]
sum : 2
you send: [60,50]
sum : 1
you send: [61,51]
No código acima,
output_str="[%d,%d]" % (max_blob.cx,max_blob.cy) # forma 1
e
output_str=json.dumps([max_blob.cx,max_blob.cy]) # forma 2
O resultado é o mesmo, pois a estrutura é simples; você pode usar a função de formatação de strings do Python ou a função de conversão do JSON.
No resultado, mesmo que múltiplos blocos de cor sejam encontrados, apenas as coordenadas do maior bloco de cor são enviadas.