오늘이야 말로 끝내 보겠다!
3일차 시작합니다.
.
.
.
2일차를 마치며 마우스의 절대 위치를 사용하려 했는데
마우스 축이 틀어졌을 경우 영점을 초기화 하려는 목적이였습니다.
허나 생각을 해보니
리셋버튼을 누른 상태에서는 마우스를 고정 시키면
축을 조정할수 있을것 같더군요
한번 이걸로 코드를 짜 보았습니다.
float minActivex = 0.2;
float minActivey = 0.02;
int sensitivex = 50;
int sensitivey = 100;
float difex = nex - ex;
float difey = ney - ey;
//마우스 이동거리 초기화
mousex = 0;
mousey = 0;
//각도가 음수에서 양수, 양수에서 음수 갈때 처리
if(difex > 360){
difex -= 360;
}else if(difex < -360){
difex += 360;
}
if(difey > 360){
difey -= 360;
}else if(difey < -360){
difey += 360;
}
Serial.print("difx\t");
Serial.print(difex);
Serial.print("dify\t");
Serial.println(difey);
//최소 반응 수치보다 높으면 반영 + 민감도 배율
if(difex > minActivex || difex < -(minActivex)){
mousex = int(difex*sensitivex);
}
if(difey > minActivey || difey < -(minActivey)){
mousey = int(difey*sensitivey);
}
ex = nex;
ey = ney;
ez = nez;
//버튼 누른 상태에서 영점 조절
if(digitalRead(RESETBUTTON) == LOW){
Mouse.move(mousex, mousey, false);
Serial.print("xy\t");
Serial.print(mousex);
Serial.print("\t");
Serial.println(mousey);
저작권 때문에 제가 만든 부분만 올렸습니다.
위에 내용은 ex,ey,ez에 센서의 값을 담는 다는것만 알면 이해하실수 있을겁니다.
자 이제 코드를 넣고 돌려보면
마우스 포인터가 발광하는 모습을 보실 수 있습니다.
민감도나 배율을 손봐야 겠지만 그래도 동작하는 모습을 보니 신이 납니다.
.
.
.
이제 정말 마지막 입니다.
바로 블루투스를 연결하는 작업입니다.
이것만 하면 꿈에 그리던 누워서 유튜브, 넷플릭스 생활을 즐길수 있습니다.
.
.
.
그렇게 열심히 인터넷을 뒤져본 결과
https://forum.arduino.cc/t/bluetooth-mouse-using-leonardo/304714
Bluetooth mouse using leonardo
Guys...I'm working on a project to make a 'Bluetooth head mouse' using arduino micro,lsm9ds0 and hc-05 Bluetooth module...I could successfully make a USB mouse out of arduino & lsm9ds0....but I don't know how to make it work in Bluetooth mode using hc-05..
forum.arduino.cc
그렇습니다.
사실 레오나드로 보드는 usb로 연결되었을때
입력장치로 인식 가능하지 블루투스로는 마우스 조작이 불가능 했습니다.
.
.
.
이왕 이렇게 된거 누가 이기나 한번 해 봅시다.
마우스로 인식하게 하는건 포기하고
센서값을 시리얼 통신으로 받아 파이썬 프로그램이
마우스를 움직이는 방식으로 만들어 보겠습니다.
#include <Mouse.h>
#include <Wire.h>
#include <SoftwareSerial.h>
#define BT_RXD 8
#define BT_TXD 9 //8,7 번핀 사용
SoftwareSerial BTSerial(BT_RXD, BT_TXD);
byte buffer[1024]; // 데이터를 수신 받을 버퍼
int bufferPosition; // 버퍼에 데이타를 저장할 때 기록할 위치
//scl, sda, 0
int16_t gyroX, gyroZ;
int Sensitivity = 600;
uint32_t timer;
uint8_t i2cData[14]; // Buffer for I2C data
const uint8_t IMUAddress = 0x68; // AD0 is logic low on the PCB
const uint16_t I2C_TIMEOUT = 1000; // Used to check for errors in I2C communication
void setup() {
Serial.begin(9600);
BTSerial.begin(115200);
Wire.begin();
i2cData[0] = 7; // Set the sample rate to 1000Hz - 8kHz/(7+1) = 1000Hz
i2cData[1] = 0x00; // Disable FSYNC and set 260 Hz Acc filtering, 256 Hz Gyro filtering, 8 KHz sampling
i2cData[3] = 0x00; // Set Accelerometer Full Scale Range to ±2g
while(i2cWrite(0x19,i2cData,4,false)); // Write to all four registers at once
while(i2cWrite(0x6B,0x01,true)); // PLL with X axis gyroscope reference and disable sleep mode
while(i2cRead(0x75,i2cData,1));
if(i2cData[0] != 0x68) { // Read "WHO_AM_I" register
Serial.print(F("Error reading sensor"));
while(1);
}
delay(100); // Wait for sensor to stabilize
while(i2cRead(0x3B,i2cData,6));
timer = micros();
Mouse.begin();
}
void loop() {
/* Update all the values */
while(i2cRead(0x3B,i2cData,14));
gyroX = ((i2cData[10] << 8) | i2cData[11]);
gyroZ = ((i2cData[12] << 8) | i2cData[13]);
gyroX = gyroX / Sensitivity / 1.1 * -1;
gyroZ = gyroZ / Sensitivity * -1;
Serial.print("\t");
Serial.print("x = ");
Serial.print(gyroX);
Serial.print("z = ");
Serial.print(gyroZ);
Serial.print("\r\n");
//Mouse.move(gyroZ,gyroX);
String myString = String(gyroZ)+","+String(gyroX)+".";
char* buf = (char*) malloc(sizeof(char)*myString.length()+1);
myString.toCharArray(buf, myString.length()+1);
BTSerial.write(buf);
free(buf);
delay(10);
Serial.print(myString);
Serial.print("\r\n");
}
x좌표 + "," + y좌표 + "." 형식으로 파이썬에 데이터를 전송 하면
# Importing Libraries
from ast import Try
import serial
import pyautogui
multix = 1
arduino = serial.Serial(port='COM11', baudrate=115200, timeout=10)
sumx = 0
sumy = 0
xory = 0
poOrNe = 0
finddot = 0
findrest = 0
bufferString = ""
print("연결 성공?")
while True:
if arduino.readable():
bufferString = arduino.read(50).decode()
else:
continue
# 해석
# 처음 닷 or 쉼표 까지 자르기
finddot = bufferString.find(".")
findrest = bufferString.find(",")
if(findrest>finddot):
bufferString = bufferString[finddot+1:]
else:
bufferString = bufferString[findrest+1:]
poOrNe = 1
#반복해서 저장
while True:
if(poOrNe == 0):
findrest = bufferString.find(",")
sumx += int(bufferString[:findrest])
bufferString = bufferString[findrest+1:]
poOrNe = 1
if (bufferString.find(".")==-1):
break
else:
finddot = bufferString.find(".")
sumy += int(bufferString[:finddot])
bufferString = bufferString[finddot+1:]
poOrNe = 0
if (bufferString.find(",")==-1):
break
# 마우스 움직이게
try:
print("x,y = ",sumx*multix,-sumy*multix)
pyautogui.move(sumx*multix,-sumy*multix)
except:
print("out of screen")
# 초기화
sumx = 0
sumy = 0
xory = 0
poOrNe = 0
finddot = 0
findrest = 0
bufferString = ""
이걸 50글자씩 수신한 후 문자열을 분석해 x,y 값의 합을 연산하고
그 합만큼 움직이게 해봅시다.
.
.
.
딜레이를 최대한 줄여서 버벅임을 줄여보려 했지만
자주 읽으면 파이썬에 프로그램이 느려지고
한번에 많이 읽으려면 통신을 기다려야 하는 문제는
제 실력으론 해결할 수 없어서 여기서 만족해야 할것 같습니다.
.
.
.
생각보다 길어졌지만 그래도 결과물이 나온 상태로
포스팅을 마무리 할 수 있게 되서 기쁘네요
그럼 전 이만 누워서 유튜브 시청하고 가보도록 하겠습니다.
긴 글 봐주셔서 감사합니다.
'일상 > 기타' 카테고리의 다른 글
앞으로 작업 노래 (0) | 2023.02.27 |
---|---|
에이밍 마우스 컨트롤러 제작기 2일차 (0) | 2022.07.28 |
에이밍 마우스 컨트롤러 제작기 1일차 (0) | 2022.07.21 |